Search code examples
wpftextblock

WPF Multiline TextBlock LineBreak issues


I have the following code

txtBlock1.Inlines.Add("This is first paragraph \n This is second paragraph");

then TextBlock would display:

This is first paragraph
This is second paragraph

But, if I have the following (which I though is equivalent);

txtBlock1.Inlines.Add("This is first paragraph");
txtBlock1.Inlines.Add("\n");
txtBlock1.Inlines.Add("This is second paragraph");

TextBlock display:

This is first paragraph // but second paragraph missing

If I separate out the linebreak then the rest of text after the linebreak doesn't show. Why?

I have to use run:

Run run1 = new Run();
run1.Text = "First Paragraph";
run1.Text += "\n";
run1.Text += "Second Paragraph";
txtBlock1.Inlines.Add(run1); 

Then it produce the result correctly. Why I cannot add inline text to Textblock and require me to use Run?


Solution

  • See this answer: What the best way to get paragraphs in a WPF textblock? (newline chars?)

    You need:

    txtBlock1.Inlines.Add("This is first paragraph");
    txtBlock1.Inlines.Add(new LineBreak());
    txtBlock1.Inlines.Add("This is second paragraph");