Share via


WPF: Tips - Newline in Text


Occasionally you need a TextBlock which has multiple lines of text.
This is WPF so naturally there's several ways to accomplish this.
This tip explains some options.

Sub Objects

If you've only ever used a TextBlock by setting the Text property then it might not have occurred to you that you can put multiple UI Elements within a TextBlock.
Technically speaking the things you can put in there are Inlines.
There are a few types of Inline:

As you can see, you can do quite a lot more than just a linebreak but that's what the article is about so let's see how you do that:

<TextBlock>
    <Run Text="First Line"/>
    <LineBreak/>
    <Run Text="Second Line"/>
</TextBlock>

If you're familiar with TextBlock then you might be thinking "Hang on a minute, don't you need to set TextWrapping to Wrap?  That's only if you set the text property directly.  The above works fine.

Resource

Maybe this string is actually a localised resource which will be used throughout an application and you can't just add objects to the textblock.
You can define a string with carriage return and line break in XAML as a resource, there are a couple of tricks to this though.

Here's an example Resource Dictionary.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:col="clr-namespace:System.Collections;assembly=mscorlib"
                    xmlns:sys="clr-namespace:System;assembly=mscorlib"
                    xmlns:local="clr-namespace:wpf11"
                    >
    <sys:String x:Key="TwoLines"  xml:space="preserve">First Line &#x0d;&#x0a;SecondLine</sys:String>
</ResourceDictionary>

The two things starting with &x there are hex code mappings of characters - these are XML character entities.

Seeing as these are non display characters they're a sort of white space as far as XAML is concerned and it will eat them on you unless you also include that xml:space preserve in there.

Formatted Text

You can also use that space preserve trick on the text you put as content of a TextBlock.

<TextBlock xml:space="preserve">
    First Line
    Second Line
</TextBlock>

There is a potential gotcha ( or feature ) there which you will spot if you try that markup.  
The two pieces of text will be indented because the spaces in front of them will be preserved as well as the new line.

String

If you're binding to a string property or setting the text in code you can use the usual c# escape characters, although in this case you also need to set TextWrapping="Wrap".
Markup thus:

<TextBlock Name="tb" TextWrapping="Wrap"/>

and code:

tb.Text = "First Line" + System.Environment.NewLine + "Second Line";

See Also

This article is part of the WPF Tips Series, if WPF is your area of interest then you will probably find other useful articles there.