WPF Textblock, linebreak in Text attribute

Viewed 102601

Is there a way to have \n make a line break in a TextBlock?

<TextBlock Text="line1\nLine2" />

Or is there a better way to force a middle line break, inside the Text attribute?

<LineBreak />

This doesn't work for me, it needs to be the value of the Text attribute, because the text string is being set from an outside source.

I'm familiar with LineBreak but it's not the answer I'm looking for.

16 Answers

Try this:

<TextBlock>
    line1
    <LineBreak />
    line2
</TextBlock>

How about breaking the line into two tags?

<StackPanel>
    <TextBlock Text="Line1" />
    <TextBlock Text="Line2" />
</StackPanel>

Correct way to use it may be the following :

<TextBlock>  
    <Span>text1</Span>  
    <LineBreak/>  
    <Span>text2</Span>  
</TextBlock>

The Best way that worked for me for multiple lines in the same Textblock is:

<TextBlock>  
    text1  
    <LineBreak/>  
    text2  
</TextBlock>

Make sure to not use TextWrapping="Wrap". Use TextWrapping="NoWrap" or use nothing.

This also works fine:

<TextBlock>
    <Run Text="My nice text"/>
    <LineBreak/>
    <LineBreak/>
    <Run Text="After some linebreaks, I'm back!"/>
</TextBlock>

this &amp;#10; did not work for me, when I used binding. But this works:

$"first line {Environment.NewLine} second line"

This also works fine.

Using this method we can modify the text properties in each line as we required.

<TextBlock>
    <StackPanel>
        <TextBlock FontSize="12" FontWeight="Bold" >My Text One</TextBlock>
        <TextBlock FontFamily="Times New Roman" FontStyle="Italic">
            - My Text Two
        </TextBlock>
    </StackPanel>
</TextBlock>
Related