WPF and string formatting

2019-05-07 09:22发布

问题:

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:

You can use XML character escaping

<TextBlock Text="Hello&#13;World!"/>


回答2:

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>


回答3:

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


回答4:

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.