25

Maybe I'm not using the right key words, but all my searches are coming up empty. How do you force a line break?

I can tell you that none of the following work:

<Label
    Content="Line&br;Break:" />

<Label
    Content="Line<br />Break:" />

<Label
    Content="Line
    Break:" />

<Label
    Content="Line\nBreak:" />

Can someone share this closely guarded secret?

Thanks.


EDIT:

Okay, never mind. I finally found it.

<Label
    Content="Line&#x0a;Break:" />

Definitely not easy to guess!


EDIT 2:

Okay, and now to get the text to be right-justified, I went with this:

<Label>
    <TextBlock
        TextAlignment="Right"
        Text="Line&#x0a;Break:" />
</Label>

Thanks to Julien for the idea of using a TextBlock.

devuxer
  • 41,681
  • 47
  • 180
  • 292

3 Answers3

26

If you only need to display text, you can use a TextBlock instead of a Label:

<TextBlock>
  Line<LineBreak/>Break:
</TextBlock>

If you really need a Label (e.g. you need to respond to a click event), you can wrap the above code inside a Label.

Julien Poulin
  • 12,737
  • 10
  • 51
  • 76
  • I don't need it to respond to a click event, but I do need it to gray out when disabled (which I believe TextBlock won't do without extra code/markup). However, I'm now having a problem trying to right justify the text of my label, so I might need to use something else. HorizontalAlignment="Right" and HorizontalContentAlignment="Right" both have no effect. – devuxer Aug 01 '09 at 07:56
  • You can set the TextAlignment property of the TextBlock to Right. As for the gray out, it's going to require extra markup. – Julien Poulin Aug 01 '09 at 09:05
  • Thanks, Julien. I was able to solve by putting the TextBlock inside a Label (see my edits above). – devuxer Aug 01 '09 at 17:25
10

If you want a new line in a label:

<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)

Tabrez Shaikh
  • 101
  • 1
  • 6
1

I'd do this:

<StackPanel>
    <Label>First line</Label>
    <Label>Second line</Label>
</StackPanel>

If the formatting gets really involved, I'd use FlowDocumentScrollViewer.

Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
  • 1
    This is not the intended way. Because they're separate controls, you have to deal with margins etc... (it acts more like a paragraph) The TextBlock with LineBreaks is much cleaner! – Jowen Apr 27 '10 at 11:27
  • Some advanced/custom controls don't accept that linebreak like that however. This should always work, and is at least a good alternative to keep in mind. – Gregor A. Lamche Sep 14 '20 at 10:57