What is the best way to get paragraphs in a WPF text block? (newlines?)

I have text that has newline markers "\ r \ n". I would like to have newlines in a WPF text block. I tried replacing "\ r \ n" with "& # 13;" (no spaces), which worked when I set the Text property to XAML, but didn't seem to work when setting up from C # code.

So ... what is the standard way to convert "\ r \ n" to newlines in a WPF text block?

thanks in advance!

[Edit] Having received the answers here, I pass the text with the new characters "\ r \ n" to the WPF text block. It works great, but in terms of coding, can anyone confirm that this is a reasonable way to go?

// assign the message, replacing "\r\n" with WPF line breaks string[] splitter = new string[] { "\r\n" }; string[] splitMessage = message.Split(splitter, StringSplitOptions.None); int numParagraphs = splitMessage.Count(); if (numParagraphs == 1) { this.Message.Text = message; } else { // add all but the last paragraph, with line breaks for (int i = 0; i < splitMessage.Count() - 1; i++) { string paragraph = splitMessage[i]; this.Message.Inlines.Add(new Run(paragraph)); this.Message.Inlines.Add(new LineBreak()); } // add the last paragraph with no line break string lastParagraph = splitMessage[splitMessage.Count() - 1]; this.Message.Inlines.Add(new Run(lastParagraph)); } 

[/ Edit]

+7
newline wpf textblock
source share
3 answers

Try this for a more WPF-oriented solution.

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

See also: XAML Response

+25
source share
 textBlock.Text = string.Format("One{0}Two", Environment.NewLine); 
+6
source share

When writing C #, I always use "System.Environment.Newline" to return a newline carriage.

This means that you don’t need to worry about character encoding or what the target OS is using.

I also found that it works with WPF GUI when called from the main .cs file.

0
source share

All Articles