WPF TextBox/TextBlock 文本超出顯示時,文本靠右顯示


文本框顯示

文本框正常顯示:

文本框超出區域顯示:

 

 實現方案

判斷文本框是否超出區域

請見《TextBlock IsTextTrimmed 判斷文本是否超出

設置文本布局顯示

1. FlowDirection

當文本超出顯示區域時,設置FlowDirection靠右顯示

下面是封裝的附加屬性ScrollEndWhenTextTrimmed

 1         /// <summary>
 2         /// 當文本超出顯示時,文本是否靠右側顯示
 3         /// </summary>
 4         public static readonly DependencyProperty ScrollEndWhenTextTrimmedProperty = DependencyProperty.RegisterAttached(
 5         "ScrollEndWhenTextTrimmed", typeof(bool), typeof(TextBoxHelper),
 6         new PropertyMetadata(default(bool), OnScrollEndWhenTextTrimmedChanged));
 7 
 8         private static void OnScrollEndWhenTextTrimmedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
 9         {
10             var textBox = (TextBox)d;
11             textBox.TextChanged -= TextBoxOnTextChanged;
12             if ((bool)e.NewValue)
13             {
14                 textBox.FlowDirection = IsTextTrimmed(textBox) ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
15                 textBox.TextChanged += TextBoxOnTextChanged;
16             }
17             void TextBoxOnTextChanged(object sender, TextChangedEventArgs args)
18             {
19                 textBox.FlowDirection = IsTextTrimmed(textBox) ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
20             }
21         }
22 
23         public static void SetScrollEndWhenTextTrimmed(DependencyObject element, bool value)
24         {
25             element.SetValue(ScrollEndWhenTextTrimmedProperty, value);
26         }
27 
28         public static bool GetScrollEndWhenTextTrimmed(DependencyObject element)
29         {
30             return (bool)element.GetValue(ScrollEndWhenTextTrimmedProperty);
31         }

 

在需要設置文本超出時居右顯示的TextBox控件中,添加附加屬性ScrollEndWhenTextTrimmed即可。

2.ScrollToEnd

類似方案FlowDirection,文本超出時,通過滾動到文本末尾后,文本靠右顯示。

如方案FlowDirection,可以在添加附加屬性更改事件中,訂閱TextBox的TextChanged。

1     textBox.SelectionStart = textBox.Text.Length;
2     textBox.ScrollToEnd();

But,此方案有缺陷。當TextBox設置IsEnabled=false時,就無法滾動到了。即使如下設置依然無效:

1     textBox.IsEnabled = true;
2     textBox.SelectionStart = textBox.Text.Length;
3     textBox.ScrollToEnd();
4     textBox.IsEnabled = false;

當然,如果文本框不設置IsEnabled時,此方案是可行的。

注:如上方案,本來通過SelectionStart直接綁定TextBox自身的Text.Length就行。然而SelectionStart不是依賴屬性,只能直接賦值~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM