How to get the trimmed text of the TextBlock when TextTrimming is set to "WordEllipsis" or "CharacterEllipsis" ?
For example, this code:
<TextBlock Name="text1" FontSize="12" Width="94" Text="THIS IS A LONG TEXT" TextTrimming="WordEllipsis"/>
displays: THIS IS A...
How to get the trimmed text: LONG TEXT or the index where the string is trimmed: 10
You need to manually measure the text (with all the font styling applied).
A general solution that also works with
TextTrimmingset toTextTrimming.WordEllipsiswould have to iteratively find the last character position.Because there is nor related API we must do it the hard way and iteratively test until we don't get an exception anymore. There is no other way (the requirement to known the exact text portion that clips the available text area is usually not sensible).
However, when
TextTrimmingis set toTextTrimming.CharacterEllipsisthere won't be any exceptions thrown. This is because character based trimming produces a predictable result opposed to word trimming where the length of the words is random (because the words are not known). This means theTextTrimming.CharacterEllipsisbased case is more performance friendly.Additionally, finding the multiple hidden text ranges of a multi-line
TextBlockis a more complex scenario that is not addressed by the proposed solution.The final solution that supports
TextTrimming.WordEllipsisandTextTrimming.CharacterEllipsiscould look as follows: