在WPF中将回车符添加到字符串资源

时间:2010-10-20 00:50:56

标签: wpf textblock carriage-return

我的应用程序将所有本地化文本存储在字符串资源字典中,如http://msdn.microsoft.com/en-us/library/bb295251(VS.85).aspx

所示
        <ResourceDictionary 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:system="clr-namespace:System;assembly=mscorlib">

  <!-- String resource that can be localized -->
  <system:String x:Key="localizedMessage">en-US Message</system:String>

</ResourceDictionary>

我的问题是,如何在字符串资源中添加新行,并在TextBlock中使用它时正确呈现。

执行此内联工作:

<TextBlock Name="test" Text="Line 1&#13;Line 2"> </TextBlock>

但是,在字符串资源中使用&#13;不起作用。将新行添加到字符串资源的最佳方法是什么?

3 个答案:

答案 0 :(得分:18)

更新:更新回答 - 更好的选择

XAML解析器根据以下规则对空格进行规范化。

http://msdn.microsoft.com/en-us/library/cc189036(VS.95).aspx#whitespace

要指示您的sys:String保留空白,请将xml:space="preserved应用于其中:

<sys:String x:Key="MyLocalizedString" xml:space="preserve">this&#13;&#10;is&#13;&#10;my&#13;&#10;resource</sys:String>

答案 1 :(得分:13)

在资源视图中输入字符串资源时,可以通过按Shift + Enter添加CR / LF。它将添加换行符,您将能够看到它。检索资源字符串并将其设置为文本块上的文本将产生再现换行符(或多个换行符)的期望效果。在我的情况下,我想在单个文本块中模拟两个段落。我不喜欢其他方法,因为它需要翻译成另一种语言来处理两个字符串。我想将此视为单个字符串资源,以便翻译人员具有他们所翻译的完整上下文。

答案 2 :(得分:0)

所以,它显然已经有一段时间,但对于那些在我的情况下,这或许会有所帮助。就我而言,我有一个独立的XML资源文件,我已经在使用...

var strVal = (string)Application.Current.FindResource(key);
return strVal;

...在我自己的帮助器类中加载资源字符串。所以对我来说,最简单的解决方案是只需插入对Replace的调用,如下所示:

var strVal = (string)Application.Current.FindResource(key);
strVal = strVal.Replace(@"\n", Environment.NewLine);
return strVal;

我的StringResources.xaml中的示例允许我使用转义字符 \ n ,如下所示....

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:system="clr-namespace:System;assembly=mscorlib">

    <system:String x:Key="resKeyValue1">The source field "{0}" is already mapped to the destination field "{1}".\n\n
    Do you want to additionally map the source field "{0}" to the destination field "{2}"?</system:String>

    ...
</ResourceDictionary>