Render just the first line of a TextBlock

Render just the first line of a TextBlock

Sometimes you want a TextBlock to just display one line. For example if you have a huge virtualized ListView that contains many data items and in the DataTemplate you’re using a TextBlock. When the TextBlock has different height, the virtualization leads to some not so nice behavior when scrolling:

The Thumb of the ScrollBar changes its size while scrolling, as the final extend size is not known, as the items in the ListView have different sizes because of multiple lines.

So when you have virtualization, you might want to display your multiline messages in a master-detail-way. Select a single-line-item in the ListView and display the multiline message somewhere else.

But now the problem is, how to tell the TextBlock to render just the first line? Note that I want to adjust the rendering. I don’t want to adjust the strings with a converter or whatever. Just the rendering! :-)

The TextBox has for the single-line-scenario a MaxLines-Property. But the TextBlock does not have this property.
The TextBlock also does not allow to override its MeasureOverride-method to measure the line height and do custom stuff, as this method is marked as sealed in the TextBlock class.

So how could you display only the first line of a TextBlock like this:

To render just the first line, I use a little trick. I place the TextBlock from above together with a hidden TextBlock with just one line in a Grid. Then I can bind the real TextBlock’s Height to the ActualHeight of the hidden one-line-TextBlock. Here the XAML-code, works like a charm.

Note that you could place the hidden one-liner-TextBlock also somewhere else, especially if you have thousands of records that would use a TextBlock via a DataTemplate

Share this post