Search code examples
wpftrimtextblock

Customise text trimming in WPF TextBlock


There is a TextBlock element in my WPF view and it is data-bound to a string property in the view model. Now the text in this property can get a bit longer so it should be trimmed to be displayed in a single line. The layout should not be changed, so using multiple lines must be avoided. Also the data binding source should not be changed and remain a single string. The text to be displayed looks like the following examples:

  • Some object of XY
  • Another object of ABC
  • 3 blurb objects (XY, ABC, DEF)
  • 20 awesome objects (XY #1, #2, ABC #2, #3, DEF, GHI, and, some, more)

The simple solution is this:

<TextBlock Text="{Binding PageTitle}" TextTrimming="CharacterEllipsis"/>

This works fine for the first two example texts, but in the last two samples, I would like the closing parenthesis to remain visible. So what I currently get is this:

  • 20 awesome objects (XY #1, #2, ABC #2, #3, DEF...

But what I seek for is this:

  • 20 awesome objects (XY #1, #2, ABC #2, #3, DEF...)

Is there a simple way in WPF to do that? Basically, the ellipsis string, which is now always three dots (visually, might also be the Unicode character for that), needs to be variable and include whatever closing punctuation is included in the source string.

I could write a custom control for that, if necessary, but need help on the implementation of the trimming, too.


Solution

  • Simple approach: use a DockPanel, put two TextBlocks in it, the first one displays your string with a ellipsis trimming, and the second one showing the closing parenthesis, docked to the right:

    <DockPanel>
        <TextBlock Text=")" DockPanel.Dock="Right" />
        <TextBlock Text="{Binding PageTitle}" TextTrimming="CharacterEllipsis" />
    </DockPanel>
    

    If you want to do the trimming yourself, you can have a look at my answer in this post: Ellipsis at start of string in WPF ListView.