WPF MultiLine TextTrimming

1.2k Views Asked by At

We have a case where we need to display Character Ellipsis(i.e. show text as trimmed) when we have multiline text.

The textblock shows trailing ellipsis when the content is anyway bigger than the width of the multiline TextBlock (i.e. TextWrapping is set to Wrap).

But we have a case wherein, we need to show only one line with ellipsis whether the text width of the first line is greater than the width of textblock or not.

For example, consider the following sample text

String str = "1\n2\n3456\n45889";
textBlock.Text = str;

The TextBlock should display as shown below:

1...

and the ToolTip will show the entire text. I tried doing some research on the possibilities but could not find much help and was wondering if anyone in the community has encountered such a situation or perhaps could suggest me?

Since, we shouldn't change the underlying data object (real time scenario) but only change what is rendered to the user, I am guessing a Converter should do the trick but I am still stuck on how to proceed. Or do you guys have any other alternatives?

1

There are 1 best solutions below

0
On

Create a custom control based off of the textblock which handles the business logic needed for the ellipse.

The binding of the actual text to a specific property can ensure that the text is not changed. While in a separate property you have the visual text with the ellipse which gets updated when the original text changes (the dependency property change event) and the visual text subsequently displayed on the screen. Also have the tooltip bound to the original text which helps in that scenario of showing the actual text and not the ellipsed text.

By creating an easy custom control you have the ability to handle the business logic all in one location and it can be used in other screens and projects.