Newline in a WPF-label?

WpfLabelNewline

Wpf Problem Overview


How can I add a newline in the text of a label in WPF such as the following?

<Label>Lorem 
  ipsum</Label>

Wpf Solutions


Solution 1 - Wpf

<Label><TextBlock>Lorem<LineBreak/>ipsum</TextBlock></Label>

You need to use TextBlock because TextBlock accepts as children a collection of Inline objects. So you are giving the TextBlock element three Inline items: Run Text="Lorem", LineBreak, and Run Text="ipsum".

You can't do the following:

<Label>Lorem<LineBreak/>ipsum</Label>`

because a label accepts one content child element.

Also, not sure exactly what your use case is but notice I placed a TextBlock inside your Label element. Is it repetitive? Not really, depending on your need. Here's a good article on the differences between the two elements: Difference between Label and TextBlock

Solution 2 - Wpf

in WPF you can use the value "&#10;" or "&#xA;"

For example:

<Label Content="Lorem&#10;ipsum" />

("10" is the ASCII number for newline)

or

<Label Content="Lorem&#xA;ipsum" />

("A" is the ASCII number for newline in hex)

Example, with a border arround label to show boundry

Solution 3 - Wpf

When doing this in the ViewModel or Model, I have found that using Environment.NewLine has the most consistent outcome, including localization. It should work directly in the View as well, but I haven't tested that.

Example:

In the View

<Label Content="{Binding SomeStringObject.ParameterName}" />

In the ViewModel:

SomeStringObject.ParameterName = "First line" + Environment.NewLine + "Second line";

Solution 4 - Wpf

<Label xml:space="preserve">text content
another line</Label>

seems to work too

Solution 5 - Wpf

An example of how to add a ToolTip with multiple lines to a control, such as a button. The tooltip is width limited so it will wrap if a sentence is too wide.

<!-- Button would need some properties to make it clickable.-->
<Button>
   <Button.ToolTip>
      <TextBlock Text="Line 1&#x0a;Line 2" MaxWidth="300" TextWrapping="Wrap"/>
    </Button.ToolTip>
</Button>

Tested on VS2019 + .NET 4.6.1 + WPF.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNatriumView Question on Stackoverflow
Solution 1 - WpfSzymon RozgaView Answer on Stackoverflow
Solution 2 - Wpf00jtView Answer on Stackoverflow
Solution 3 - WpfHeyZikoView Answer on Stackoverflow
Solution 4 - WpfKarlView Answer on Stackoverflow
Solution 5 - WpfContangoView Answer on Stackoverflow