2014-08-28 32 views
3

在我的WPF应用程序中,我引用了来自集中字典资源的字符串。我怎样才能在这些字符串中插入换行符?我试过"line1\nline2", "line1\\nline2" and "line1
line2",但都没有工作。WPF行中的字符串资源中断

我应该提到,我还在这些字符串({0},...)中包含了令牌,后来在运行时使用了string.format(resource,args)。

+0

如果你需要放行breaksa,为什么不把字符串分成两个不同的字符串? – Juan 2014-08-28 09:15:29

+0

您应该将'xml:space =“preserve”'添加到您的ResourceDictionary或单个资源中。 – marbel82 2017-06-12 11:19:53

回答

8

工作方案:shift +在visual studio的词典资源窗口中输入似乎工作。

2

尝试十六进制文字:

<sys:String>line1&#13;line2</sys:String> 

但是请注意,如果你实际上是编码Inline你可以使用:

<LineBreak /> 

如:

<TextBlock> 
    <TextBlock.Text> 
     line1 <LineBreak /> line2 
    </TextBlock.Text> 
</TextBlock> 
3

尝试将xml:space="preserve"加入您的资源并使用&#13

<sys:String x:Key="MyString" xml:space="preserve">line1&#13line2</sys:String> 
+1

xml:space =“preserve”在我的测试中打破它。另外请注意,您忘记了分号。 – codekaizen 2014-08-28 09:24:22

1

如果什么都没有解决,那么有保证的解决方案就是使用转换器。

public class NewLineConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     var s = string.Empty; 

     if (value.IsNotNull()) 
     { 
      s = value.ToString(); 

      if (s.Contains("\\r\\n")) 
       s = s.Replace("\\r\\n", Environment.NewLine); 

      if (s.Contains("\\n")) 
       s = s.Replace("\\n", Environment.NewLine); 

      if (s.Contains("&#x0a;&#x0d;")) 
       s = s.Replace("&#x0a;&#x0d;", Environment.NewLine); 

      if (s.Contains("&#x0a;")) 
       s = s.Replace("&#x0a;", Environment.NewLine); 

      if (s.Contains("&#x0d;")) 
       s = s.Replace("&#x0d;", Environment.NewLine); 

      if (s.Contains("&#10;&#13;")) 
       s = s.Replace("&#10;&#13;", Environment.NewLine); 

      if (s.Contains("&#10;")) 
       s = s.Replace("&#10;", Environment.NewLine); 

      if (s.Contains("&#13;")) 
       s = s.Replace("&#13;", Environment.NewLine); 

      if (s.Contains("<br />")) 
       s = s.Replace("<br />", Environment.NewLine); 

      if (s.Contains("<LineBreak />")) 
       s = s.Replace("<LineBreak />", Environment.NewLine); 
     } 

     return s; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
}