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:

<TextBlock TextWrapping="NoWrap">
  Text with
    <LineBreak/>
  multiple
    <LineBreak/>
  lines
</TextBlock>

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.

<Grid>
  <TextBlock x:Name="txtOneLineDummy" 
             Text="One line" 
             Visibility="Hidden" 
             VerticalAlignment="Top"/>
  <TextBlock TextWrapping="NoWrap" 
             Height="{Binding ElementName=txtOneLineDummy,Path=ActualHeight}">
    Text with
      <LineBreak/>
    multiple
      <LineBreak/>
    lines
  </TextBlock>
</Grid>

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

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.