【问题标题】:WPF and string formattingWPF 和字符串格式化
【发布时间】:2010-09-12 00:58:26
【问题描述】:

假设我有一些这样的 XAML:

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

显然我想在 MyClass.Text 属性中添加一个换行符,但 XAML 解析器使用文字字符串“foo\nbar”构造对象。

是否有 (a) 一种方法可以说服解析器翻译转义序列,或 (b) 一种 .NET 方法以 C# 编译器的方式解释字符串?

我意识到我可以去那里寻找\n 序列,但最好有一个通用的方法来做到这一点。

【问题讨论】:

    标签: c# wpf xaml escaping


    【解决方案1】:

    您可以使用 XML 字符转义

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

    【讨论】:

    • 我认为有几个响应会起作用,但这肯定是最简单的解决方案。谢谢大家。
    【解决方案2】:

    别想了,试试吧;

    1. 也许是自定义绑定表达式?

    &lt;v:MyClass x:Key="whatever" Text="{MyBinder foo\nbar}"/&gt;

    1. 使用字符串静态资源?

    2. 将 Text 设为控件的默认属性,并且;

    <v:MyClass x:Key="whatever">
    foo
    bar
    </v:MyClass>
    

    【讨论】:

      【解决方案3】:

      我意识到我可以去那里寻找 \n 序列,[...]

      如果您只关心\n,那么您可以尝试以下方法:

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

      或者,对于 b),因为我不知道也找不到执行此操作的内置函数,例如:

      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】:

        我会在这里使用默认的 TextBlock 控件作为参考。在该控件中,您可以像这样进行换行:

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

        通过将控件的内容值设置为文本属性,您应该能够对控件执行类似的操作。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-05-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-31
          • 2013-05-02
          • 1970-01-01
          相关资源
          最近更新 更多