[英]Listening to changes in the Text property of the WPF TextBlock control
For a WPF TextBlock, setting the TextTrimming to TextTrimming.CharacterEllipsis will cause it to automatically cut off the text before it overflows and add some ellipses to the end. 对于WPF TextBlock,将TextTrimming设置为TextTrimming.CharacterEllipsis将导致它在文本溢出之前自动切断文本,并在末尾添加一些椭圆。 This article shows how to check if the text is being trimmed and automatically show the full text in a tooltip when it is.
本文介绍如何检查文本是否被修剪,并在工具提示时自动显示全文。
It does this, without subclassing TextBlock, by registering an event handler that listens to the SizeChanged event: 通过注册侦听SizeChanged事件的事件处理程序,无需子类化TextBlock即可完成此操作:
EventManager.RegisterClassHandler(
typeof( TextBlock ),
FrameworkElement.SizeChangedEvent,
new SizeChangedEventHandler( OnTextBlockSizeChanged ),
true );
The trouble is, this only reacts to size changed events - it works fine if the text overflows because you shrank the control, but not if it overflows because you changed the text. 麻烦的是,这仅对更改大小的事件起作用-如果由于收缩控件而导致文本溢出,则工作正常,但如果由于更改了文本而导致溢出,则无法正常工作。
Unfortunately, although the TextBlock does have a SizeChangedEvent, it doesn't have a TextChangedEvent. 不幸的是,尽管TextBlock确实具有SizeChangedEvent,但它没有TextChangedEvent。 I thought of listening to the TargetUpdated event:
我想到了听TargetUpdated事件:
EventManager.RegisterClassHandler(
typeof(TextBlock),
Binding.TargetUpdatedEvent,
new EventHandler<DataTransferEventArgs>(OnTextBlockTextChanged),
true);
But that didn't have any discernable effect, even with the NotifyOnTargetUpdated property set to true. 但是,即使将NotifyOnTargetUpdated属性设置为true,也没有任何明显的效果。 I also tried overriding the metadata on the TextProperty but it seems that can really only be done in its static constructor - in this case the TextBlock's static constructor.
我还尝试覆盖TextProperty上的元数据,但似乎只能在其静态构造函数中完成-在这种情况下,是TextBlock的静态构造函数。 Is there any way of achieving this without subclassing TextBlock?
没有子类化TextBlock,有什么方法可以实现?
You can use DependencyPropertyDescriptor
: 您可以使用
DependencyPropertyDescriptor
:
var descriptor = DependencyPropertyDescriptor.FromProperty(TextBlock.TextProperty, typeof(TextBlock));
descriptor.AddValueChanged(...);
PS. PS。 Why on Earth
TextBlock
does not have an IsTrimmed
property is beyond me. 为什么在地球上
TextBlock
没有IsTrimmed
属性,这超出了我的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.