Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 311
Only Bolivian Here Avatar asked Dec 15 '11 19:12

Only Bolivian Here


People also ask

How do I create a line break in TextBlock WPF?

Adding Line Breaks Sometimes you will want to insert a line break within a TextBlock. You can do this with a LineBreak inline, added as an XAML element within the text. A new line will be started at the position of this element.

How do you add a line in WPF?

To draw a line, create a Line element. Use its X1 and Y1 properties to set its start point; and use its X2 and Y2 properties to set its end point. Finally, set its Stroke and StrokeThickness because a line without a stroke is invisible. Setting the Fill element for a line has no effect, because a line has no interior.

How do you insert a line break in XAML?

XAML attributes of type String may contain any special characters, as long as those are referenced as hex-codes. For example, a simple line break ( \n ) would be represented as &#x0a; , for \r\n you'd use &#x0d;&#x0a; and so on.

How do I create a new line in C#?

By using: \n – It prints new line. By using: \x0A or \xA (ASCII literal of \n) – It prints new line.


2 Answers

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> 
like image 150
H.B. Avatar answered Oct 15 '22 20:10

H.B.


For completeness: You can also do this:

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

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

like image 39
Ketobomb Avatar answered Oct 15 '22 20:10

Ketobomb