How to put a new line into a wpf TextBlock control?

C#WpfNewlineTextblock

C# Problem Overview


I'm fetching text from an XML file, and I'd like to insert some new lines that are interpreted by the textblock render as new lines.

I've tried:

<data>Foo bar baz \n baz bar</data>

But the data is still displayed without the new line. I set the contents of <data> via the .Text property via C#.

What do I need to put in the XML in order for it to render the new line in the GUI?

I've tried something like this manually setting the text in the XAML:

<TextBlock Margin="0 15 0 0" Width="600">
There &#10;
is a new line.
</TextBlock>

And while the encoded character doesn't appear in the GUI it also doesn't give me a new line.

C# Solutions


Solution 1 - C#

You can try putting a new line in the data:

<data>Foo bar baz 
 baz bar</data>

If that does not work you might need to parse the string manually.

If you need direct XAML that's easy by the way:

<TextBlock>
    Lorem <LineBreak/>
    Ipsum
</TextBlock>

Solution 2 - C#

For completeness: You can also do this:

 <TextBlock Text="Line1&#x0a;Line 2"/>

x0A is the escaped hexadecimal Line Feed. The equivalent of \n

Solution 3 - C#

you must use

 < SomeObject xml:space="preserve" > once upon a time ...
      this line will be below the first one < /SomeObject>

Or if you prefer :

 <SomeObject xml:space="preserve" />  once upon a time... &#10; this line below < / SomeObject>
         

watch out : if you both use &10 AND you go to the next line in your text, you'll have TWO empty lines.

here for details : http://msdn.microsoft.com/en-us/library/ms788746.aspx

Solution 4 - C#

You can also use binding

<TextBlock Text="{Binding MyText}"/>

And set MyText like this:

Public string MyText
{
    get{return string.Format("My Text \n Your Text");}
}

Solution 5 - C#

Even though this is an old question, I've just come across the problem and solved it differently from the given answers. Maybe it could be helpful to others.

I noticed that even though my XML files looked like:

<tag>
 <subTag>content with newline.\r\nto display</subTag>
</tag>

When it was read into my C# code the string had double backslashes.

\\r\\n

To fix this I wrote a ValueConverter to strip the extra backslash.

public class XmlStringConverter : IValueConverter
{
    public object Convert(
        object value,
        Type targetType,
        object parameter,
        CultureInfo culture)
    {
        string valueAsString = value as string;
        if (string.IsNullOrEmpty(valueAsString))
        {
            return value;
        }

        valueAsString = valueAsString.Replace("\\r\\n", "\r\n");
        return valueAsString;
    }

    public object ConvertBack(
        object value,
        Type targetType,
        object parameter,
        CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Solution 6 - C#

If all else fails you can also use

"My text needs a line break here" + System.Environment.NewLine + " This should be a new line"

Solution 7 - C#

<TextBlock Margin="4" TextWrapping="Wrap" FontFamily="Verdana" FontSize="12">
        <Run TextDecorations="StrikeThrough"> Run cannot contain inline</Run>
        <Span FontSize="16"> Span can contain Run or Span or whatever 
            <LineBreak />
        <Bold FontSize="22" FontFamily="Times New Roman" >Bold can contains 
            <Italic>Italic</Italic></Bold></Span>
</TextBlock>

Solution 8 - C#

Using System.Environment.NewLine is the only solution that worked for me. When I tried \r\n, it just repeated the actual \r\n in the text box.

Solution 9 - C#

Insert a "line break" or a "paragraph break" in a RichTextBox "rtb" like this:

var range = new TextRange(rtb.SelectionStart, rtb.Selection.End); 
range.Start.Paragraph.ContentStart.InsertLineBreak();
range.Start.Paragraph.ContentStart.InsertParagraphBreak();

The only way to get the NewLine items is by inserting text with "\r\n" items first, and then applying more code which works on Selection and/or TextRange objects. This makes sure that the \par items are converted to \line items, are saved as desired, and are still correct when reopening the *.Rtf file. That is what I found so far after hard tries. My three code lines need to be surrounded by more code (with loops) to set the TextPointer items (.Start .End .ContentStart .ContentEnd) where the Lines and Breaks should go, which I have done with success for my purposes.

Solution 10 - C#

        StringBuilder somestext = new StringBuilder();
        somestext.AppendLine("this is some text on line 1");
        somestext.AppendLine(TB_Tag_Linebreak);
        somestext.AppendLine("this is some more text on line 2"); 
        return somestext.ToString();

Solution 11 - C#

You have to ensure that the textblock has this option enabled:

AcceptsReturn="True"

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
QuestionOnly Bolivian HereView Question on Stackoverflow
Solution 1 - C#H.B.View Answer on Stackoverflow
Solution 2 - C#KetobombView Answer on Stackoverflow
Solution 3 - C#GameAlchemistView Answer on Stackoverflow
Solution 4 - C#GordonView Answer on Stackoverflow
Solution 5 - C#Dan VogelView Answer on Stackoverflow
Solution 6 - C#AdrianView Answer on Stackoverflow
Solution 7 - C#alkkView Answer on Stackoverflow
Solution 8 - C#Order23View Answer on Stackoverflow
Solution 9 - C#JoshView Answer on Stackoverflow
Solution 10 - C#jlazzView Answer on Stackoverflow
Solution 11 - C#DaveView Answer on Stackoverflow