Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What the best way to get paragraphs in a WPF textblock? (newline chars?)

I have some text which has "\r\n" newline markers. I would like to have the newlines in a WPF textblock. I've tried replacing "\r\n" with "& # 13;" (without the spaces), which worked when I set the Text property in XAML, but doesn't seem to work when setting from the C# code-behind.

So...what's the standard way to convert "\r\n" to newlines in a WPF textblock?

like image 503
MrGreggles Avatar asked Oct 13 '09 11:10

MrGreggles


People also ask

How do I create a line break in TextBlock WPF?

Adding Line Breaks 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. If you have configured the text to be justified, the final line before the line break will not be expanded to fill the available width.

What is TextBlock WPF?

The TextBlock control provides flexible text support for UI scenarios that do not require more than one paragraph of text. It supports a number of properties that enable precise control of presentation, such as FontFamily, FontSize, FontWeight, TextEffects, and TextWrapping.

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 
 , for \r\n you'd use 
 and so on.

What is the difference between TextBlock and label in WPF?

Labels usually support single line text output while the TextBlock is intended for multiline text display. For example in wpf TextBlock has a property TextWrapping which enables multiline input; Label does not have this.


2 Answers

Try these for a more WPF centric solution.

TextBlock.Inlines.Add(new Run("First"));
TextBlock.Inlines.Add(new LineBreak());
TextBlock.Inlines.Add(new Run("Second"));

See also : XAML based Answer

like image 77
Ash Avatar answered Oct 18 '22 14:10

Ash


textBlock.Text = string.Format("One{0}Two", Environment.NewLine);
like image 33
Kent Boogaart Avatar answered Oct 18 '22 14:10

Kent Boogaart