Today I want to share with you a very nice way for customizing text wrapping on TextBlock in WPF.
Sometimes happens that displayed string are too long to be displayed entirely in a single cell and you need to split the string in multiple lines. WPF is able to automatically split long string in multiple lines via TextWrapping property. However it can happens that the line breaking algorithm used by WPF does not satisfy your requirements, especially when you need to split your application specific strings like mathematical formulas or hierarchy paths.

Lets assumes we would like to display a string in a multi line way like the following pictures:

In order to achieve these results we need to set the TextBlock in the following way:

<TextBlock Width="28"  TextWrapping="Wrap" TextTrimming="CharacterEllipse"  Text="{Binding Location}"/>
  • The TextWrapping=”Wrap” will split the displayed string in multi-lines (like the second and third pictures) using the standard unicode line breaking algorithm.
  • The TextTrimming=”CharacterEllipse” is used for trimming text and continuing with an ellipsis at the character closest to the trimming edge (as shown in last pictures).

The Text=”{Binding Location}” is used for displaying the content of Location Dependency Property that is initialized by code behind in the following way:

Location = "Building 1.Floor 1.Room 4";
Location = Location.Replace(" ", "\u00a0").Replace(".", ".\u200B");

and here explain the tricky used for customizing line breaking algorithm:

  • The first Replace() replaces the standard Space character with he Unicode Non-breaking space (U+00A0) with the side effect to deny the line breaking algorithm to break the string
  • The second Replace() puts the Unicode Zero Width Space (U+200B) after dots with the side effect to allowing the line breaking algorithm to break the string