简体   繁体   中英

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. 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:

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. I thought of listening to the TargetUpdated event:

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. 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. Is there any way of achieving this without subclassing TextBlock?

You can use DependencyPropertyDescriptor :

var descriptor = DependencyPropertyDescriptor.FromProperty(TextBlock.TextProperty, typeof(TextBlock));
descriptor.AddValueChanged(...);

PS. Why on Earth TextBlock does not have an IsTrimmed property is beyond me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM