WPF TextBox/TextBlock 文本超出显示时,文本靠右显示

时间:2023-03-08 15:55:00

文本框显示

文本框正常显示:

WPF TextBox/TextBlock 文本超出显示时,文本靠右显示

文本框超出区域显示:

WPF TextBox/TextBlock 文本超出显示时,文本靠右显示

实现方案

判断文本框是否超出区域

请见《TextBlock IsTextTrimmed 判断文本是否超出

设置文本布局显示

1. FlowDirection

当文本超出显示区域时,设置FlowDirection靠右显示

下面是封装的附加属性ScrollEndWhenTextTrimmed

         /// <summary>
/// 当文本超出显示时,文本是否靠右侧显示
/// </summary>
public static readonly DependencyProperty ScrollEndWhenTextTrimmedProperty = DependencyProperty.RegisterAttached(
"ScrollEndWhenTextTrimmed", typeof(bool), typeof(TextBoxHelper),
new PropertyMetadata(default(bool), OnScrollEndWhenTextTrimmedChanged)); private static void OnScrollEndWhenTextTrimmedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBox = (TextBox)d;
textBox.TextChanged -= TextBoxOnTextChanged;
if ((bool)e.NewValue)
{
textBox.FlowDirection = IsTextTrimmed(textBox) ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
textBox.TextChanged += TextBoxOnTextChanged;
}
void TextBoxOnTextChanged(object sender, TextChangedEventArgs args)
{
textBox.FlowDirection = IsTextTrimmed(textBox) ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
}
} public static void SetScrollEndWhenTextTrimmed(DependencyObject element, bool value)
{
element.SetValue(ScrollEndWhenTextTrimmedProperty, value);
} public static bool GetScrollEndWhenTextTrimmed(DependencyObject element)
{
return (bool)element.GetValue(ScrollEndWhenTextTrimmedProperty);
}

在需要设置文本超出时居右显示的TextBox控件中,添加附加属性ScrollEndWhenTextTrimmed即可。

2.ScrollToEnd

类似方案FlowDirection,文本超出时,通过滚动到文本末尾后,文本靠右显示。

如方案FlowDirection,可以在添加附加属性更改事件中,订阅TextBox的TextChanged。

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

But,此方案有缺陷。当TextBox设置IsEnabled=false时,就无法滚动到了。即使如下设置依然无效:

     textBox.IsEnabled = true;
textBox.SelectionStart = textBox.Text.Length;
textBox.ScrollToEnd();
textBox.IsEnabled = false;

当然,如果文本框不设置IsEnabled时,此方案是可行的。

注:如上方案,本来通过SelectionStart直接绑定TextBox自身的Text.Length就行。然而SelectionStart不是依赖属性,只能直接赋值~

WPF TextBox/TextBlock 文本超出显示时,文本靠右显示