Monday, August 20, 2007

How to measure text length in TextBlock

We already know how to measure text length in TextBox, but if you'll try to do it in TextBlock, you'll discover, that there are no properties for text length. The only thing, can looks like measurement is Block.TextHeight, that for some reason returns always NaN. What to do? Let's look into textblock properties. ActualWidth will calculate the length of textblock and it's text, based on LayoutEngine. This means, that if you'll put it into StackPanel, ActualWidth will return the full StackPanel length, but not the length of the actual text. However, if the text is bigger that available space set by LayoutEngine, then ActualWidth property will return the actual text size. So, what to do? We can put start Width of TextBlock to 0 and then resize it by code. Not quit nice solution. Maybe, let TextBlock to calculate it width itself. A lot of code with MeasureOverride? Really not. Let's bind the TextBlock Width to it's Actual Width.


<TextBlock Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualWidth}"/>


In this case, TextBlock without text inside it get 0 as width and if the text will grow, the width of textblock will grow also. Following sample demonstrate the results.



<TextBox Name="txt"/>

TextBlock Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualWidth}" Name="tb" Text="{Binding ElementName=txt, Path=Text}"/>

TextBlock Text="{Binding ElementName=tb, Path=ActualWidth}"/>



Nice, clean and useful solution. Thank you WPF.

No comments: