在我的WPF应用程序中,我正在从集中的字典资源引用字符串。如何在这些字符串中插入换行符?
我尝试过 "line1\nline2"、"line1\\nline2" 和 "line1
line2"
,但都没有起作用。
需要注意的是,我还在这些字符串中包含标记({0}等),并且稍后在运行时使用string.format(resource, args)。
解决方案:在Visual Studio中的字典资源窗口中使用shift+enter似乎可以起作用。
尝试将xml:space = "preserve"
添加到您的资源中,并使用
<sys:String x:Key="MyString" xml:space="preserve">line1 line2</sys:String>
xml:space="preserve"
+ 只需复制粘贴原始内容即可使其正常工作。 - Glitch<sys:String>line1 line2</sys:String>
内联
,您可以使用以下方法:<LineBreak />
E.g:
<TextBlock>
<TextBlock.Text>
line1 <LineBreak /> line2
</TextBlock.Text>
</TextBlock>
xml:space="preserve"
。 - faddenxml:space="preserve"
破坏了它。 - codekaizenApplication.Current.FindResource()
获取字符串资源,并将其传递给 MessageBox.Show()
,以呈现多行错误消息。如果没有使用 preserve
,它就会变成一行。(示例) - faddenpublic 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("

"))
s = s.Replace("

", Environment.NewLine);
if (s.Contains("
"))
s = s.Replace("
", Environment.NewLine);
if (s.Contains("
"))
s = s.Replace("
", Environment.NewLine);
if (s.Contains(" "))
s = s.Replace(" ", Environment.NewLine);
if (s.Contains(" "))
s = s.Replace(" ", Environment.NewLine);
if (s.Contains(" "))
s = s.Replace(" ", 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();
}
}
如果您正在使用文本编辑器处理resx文件,最好且最容易的方法是在需要新起一行时按下
Shift+Enter
这与其他答案中所述相同。
如果您从其他来源复制/粘贴文本到resx中,则Visual Studio会将文本以与原格式相同的方式粘贴,其中包括换行符。
<system:String x:Key="KeyName" xml:space="preserve">
First line of text.
Second line of text.
</system:String>
该命令将显示每行前面的所有空格。它还会显示两个额外的换行符:第一行之前和在文本中使用物理换行符后。去除空格和额外的换行符即可正常工作。
xml:space="preserve"
。 - marbel82