programmatic textblock entry with linebreaks

micahhoover picture micahhoover · Mar 23, 2013 · Viewed 11.2k times · Source

How do I programmatically add text with line breaks to a textblock?

If I insert text like this:

helpBlock.Text = "Here is some text. <LineBreak/> Here is <LineBreak/> some <LineBreak/> more.";

Then the linebreaks get interpreted as part of the string literal. I want it to be more like what would happen if I had it in the XAML.

I can't seem to do it the WPF way either:

helpBlock.Inlines.Add("Here is some content.");

Since the Add() method wants to accept objects of type "inline".

I can't create an Inline object and pass it as a parameter because it is "inaccessible due to its protection level:

helpBlock.Inlines.Add(new Windows.UI.Xaml.Documents.Inline("More text"));

I don't see a way to programmatically add runs.

I can find a ton of WPF examples of this, but nothing for WinRT.

I've also turned up a lot of XAML examples, but nothing from C#.

Answer

sa_ddam213 picture sa_ddam213 · Mar 23, 2013

You could just pass in newline \n instead of <LineBreak/>

helpBlock.Text = "Here is some text. \n Here is \n some \n more.";

Or in Xaml you would use the Hex value of newline

 <TextBlock Text="Here is some text. &#x0a; Here is &#x0a; some &#x0a; more."/>

Both results:

enter image description here