views:

1672

answers:

3

Hi,

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?

Thx in advance!

[Edit] After getting replies here, this is how I'm assigning text with "\r\n" newlines to a WPF textblock. It works fine, but in terms of coding can anyone confirm that it's 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]

+1  A: 
textBlock.Text = string.Format("One{0}Two", Environment.NewLine);

HTH, Kent

Kent Boogaart
I'm clearly missing something, lol: http://screencast.com/t/tKjtFMk8Jv
Gregg Cleland
Maybe doesn't work with SL? Anyway, I misread your question - see my updated answer. It works with WPF - not sure about SL.
Kent Boogaart
Thx for your replies. I've chosen Ash's answer, being WPF centric and as such it seems like the best way to go.
Gregg Cleland
+1  A: 

When writing C# I always use "System.Environment.Newline" for the newline carriage return.

It means that you don't have to worry about character coding or what destination OS uses.

I have also found it to work on WPF GUI when called from the underlying .cs file.

ChrisBD
Thanks for the reply. In this case I've gone with the WPF-centric solution.
Gregg Cleland
+5  A: 

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

Ash
Thanks! That's spot on and the way I've decided to go.
Gregg Cleland