WPF

WPF TextBlock Multiline

Jose Leon
Author

The WPF TextBlock allows to add labels to a form in its simplest form. We can say that the Label control is more advanced than the TextBlock one, but the TextBlock will fit most of the common scenarios. Below you can find a simple example of the TextBlock in XAML:

       Hello world!

In the previous screen shot we can see a simple label been drawn in the window. You can also check that there's no margin at the top or left but we can easily change this using the margin property.

       Hello world!

WPF TextBlock and Multilines

One of the problems that we usually confront with the TextBlock is how to deal with multiple lines, like what happens when a line or label is too big that is doesn't fit the window. For this, we can use several approaches to handle the big string. Below you can check an example with all possible variations:

       This is a very very very very very very long line of text        This is a very very very very very very long line of text        This is a very very very very very very long line of text

In the previous sample, we're dealing with the multiple lines in various ways.

  • The first one, we're just adding a LineBreak control in the middle of the string forcing it to insert a carriage return and breaking the line. This is perfect for when you want to explicitly add the line break. This is the same as the
    tag in HTML.
  • In the second TextBlock, we're just add an ellipsis at the end of the string. using the TextTrimming property. This is great for when you have long text and just don't know where to break the line. WPF will automatically add the ellipsis at the end of the window so you don't have to do these calculations yourself.
  • The third TextBlock is cutting the line using the Wrap value of the TextWrapping property. It'll simply wrap the text to fit the window as needed. Also, the calculation for wrapping is done automatically for you and it changes when the window resizes by any action from the user.

features

All posts

  • licensing
  • analytics

Easy .NET Protection

Purchase template