字符串资源中的WPF换行符

时间:2014-08-28 09:11:35

标签: c# wpf string

在我的WPF应用程序中,我引用了集中式字典资源中的字符串。如何在这些字符串中添加换行符?

我尝试了"line1\nline2", "line1\\nline2" and "line1
line2",但没有人正在使用。

我应该提一下,我还在这些字符串中包含标记({0},...),然后在运行时使用string.format(resource,args)。

5 个答案:

答案 0 :(得分:12)

工作解决方案:在Visual Studio的词典资源窗口中切换+输入似乎可行。

答案 1 :(得分:4)

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

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

答案 2 :(得分:3)

尝试十六进制文字:

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

但请注意,如果您实际编码Inline,则可以使用:

<LineBreak />

E.g:

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

答案 3 :(得分: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();
    }
}

答案 4 :(得分:1)

我没有要评论的代表,所以我将添加到 IVAAAN123 的答案中,这对我来说很好用(使用分号),但是,如果您在文本中添加任何换行符(以使其更可读,请确保 XML 中没有制表符,因此新行从页面边缘开始,而不是制表符进入页面,否则 'xml:space="preserve"' 将在每行开头包含空格:

<system:String x:Key="KeyName" xml:space="preserve">
    First line of text.&#13;
    Second line of text.
</system:String>

...将显示每行前面的所有空格。它还会显示两个额外的换行符:就在第一行之前和之后 因为还使用了文本中的物理换行符。删除空格和额外的换行符,它就可以工作了。

相关问题