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.

4 Answers 4

13

You can use XML character escaping

<TextBlock Text="Hello&#13;World!"/>
Sign up to request clarification or add additional context in comments.

1 Comment

I think that several of the responses would work, but this is certainly the simplest solution. Thanks to all.
1

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>

Comments

1

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();
    }
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.