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

156,322

Solution 1

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

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

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

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

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();
    }
}
Share:
156,322
Only Bolivian Here
Author by

Only Bolivian Here

Updated on March 21, 2021

Comments

  • Only Bolivian Here
    Only Bolivian Here about 3 years

    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.

  • Only Bolivian Here
    Only Bolivian Here over 12 years
    No, this doesn't do anything as well. I've even copy pasted the contents inside the XAML of the TextBlock with enter presses as new lines and it still displays it at once.
  • H.B.
    H.B. over 12 years
    @SergioTapia: There is a difference between having the break in some data file and XAML, the XAML parser ignores whitespace, but if you, for example, deserialize some XML using the XmlSerializer the breaks will be retained. In Xaml you need <LineBreak/>.
  • Zodman
    Zodman almost 10 years
    You don't even need the string.Format(). return "My Text \n Your Text"; works just fine.
  • vapcguy
    vapcguy about 7 years
    Along with having to add TextWrapping="Wrap" (and AcceptsReturn="True" if this were a TextBox) in the XAML on the TextBlock, you had it right, and this should be the answer - but just say to do the .Replace() on the value coming from the database - no need for a fancy function: valueAsString = valueAsString.Replace("\\r\\n", "\r\n"); Any value entered using the Return key will get written to the DB just fine - it's when C# gets a hold of it to display the value that problems are caused, as you noted. So this would need to be called onload of the text.
  • thehelix
    thehelix over 6 years
    Put the new line directly in the data...of course! Here I just spent a lot of time trying \n, <LineBreak/>, and tons of html codes to no avail. I should have tried simplest approach first.
  • rajibdotnet
    rajibdotnet about 6 years
    Useful in binding in a scenario such as this:- <TextBlock > <TextBlock.Text> <MultiBinding StringFormat="{}Name:{0}&#x0a;Code:{1}"> <Binding Path="Name"/> <Binding Path="Code" /> </MultiBinding> </TextBlock.Text> </TextBlock>
  • Aurélio Antonio
    Aurélio Antonio over 5 years
    this is the finest answer
  • Steve
    Steve almost 5 years
    AcceptsReturn is only for TextBox, not TextBlock
  • I.Step
    I.Step about 4 years
    I would add this link: stackoverflow.com/questions/9021649/… an explanation to the answer.
  • Veerakran Sereerungruangkul
    Veerakran Sereerungruangkul over 3 years
    +1 This solution works for me when I use String.Join() to my list of string. Example: String.Join(System.Environment.NewLine, manyStrings);
  • luka
    luka almost 2 years
    Great solution! I used this for my textblock Style