Thursday, May 26, 2022

Subscribing to a non-existent changed event

I needed a TextBlock control with a more pessimistic text trimming mechanism. None of the TextTrimming options were working for me, so I decided to subclass TextBlock and detect when the size or the text was changed. Then I could adjust the text as needed.

TextBlock exposes a SizeChanged event so that was easy.

AddHandler Me.SizeChanged, AddressOf me_SizeChanged

But it does not expose a TextChanged event.

AddHandler Me.TextChanged, AddressOf me_TextChanged

Text is a DependencyProperty so I can get a DependencyPropertyDescriptor and get notified whenever the value changes.

Private dpText As DependencyPropertyDescriptor
 
dpText = DependencyPropertyDescriptor.FromProperty(TextBlock.TextProperty, GetType(TextBlock))
dpText.AddValueChanged(Me, AddressOf me_TextChanged)