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不是依赖属性,只能直接赋值~
分类:
WPF/Silverlight
标签:
TextBox
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)