views:

937

answers:

4

Suppose I have some XAML like this:

<Window.Resources>
  <v:MyClass x:Key="whatever" Text="foo\nbar" />
</Window.Resources>

Obviously I want a newline character in the MyClass.Text property, but the XAML parser constructs the object with the literal string "foo\nbar".

Is there (a) a way to convince the parser to translate escape sequences, or (b) a .NET method to interpret a string in the way that the C# compiler would?

I realize that I can go in there looking for \n sequences, but it would be nicer to have a generic way to do this.

+1  A: 

Off the top of my head, try;

  1. A custom binding expression perhaps?

<v:MyClass x:Key="whatever" Text="{MyBinder foo\nbar}"/>

  1. Use a string static resource?

  2. Make Text the default property of your control and;

<v:MyClass x:Key="whatever">
foo
bar
</v:MyClass>
deepcode.co.uk
A: 

I realize that I can go in there looking for \n sequences, [...]

If all you care about is \n's, then you could try something like:

string s = "foo\\nbar";
s = s.Replace("\\n", "\n");

Or, for b) since I don't know of and can't find a builtin function to do this, something like:

using System.Text.RegularExpressions;

// snip
string s = "foo\\nbar";
Regex r = new Regex("\\\\[rnt\\\\]");
s = r.Replace(s, ReplaceControlChars); ;
// /snip

string ReplaceControlChars(Match m)
{
    switch (m.ToString()[1])
    {
        case 'r': return "\r";
        case 'n': return "\n";
        case '\\': return "\\";
        case 't': return "\t";
        // some control character we don't know how to handle
        default: return m.ToString();
    }
}
Matthew Scharley
A: 

I would use the default TextBlock control as a reference here. In that control you do line breaks like so:

    <TextBlock>
        Line 1
        <LineBreak />
        Line 2
    </TextBlock>

You should be able to do something similar with your control by making the content value of your control be the text property.

SmartyP
+10  A: 

You can use XML character escaping

<TextBlock Text="Hello&#13;World!"/>
Vriff Polo
I think that several of the responses would work, but this is certainly the simplest solution. Thanks to all.
chrisd