我有这个例子ResourceDictionary
:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib"
xml:space="preserve">
<!--New line: 
-->
<s:String x:Key="Example.Line">New
Line</s:String>
</ResourceDictionary>
如果它已经在项目中并且我将其绑定到控件(例如TextBlock
和{DynamicBinding Example.Line}
,则一切都按预期工作。 (两个词在不同的行中)
现在,如果我使用.xaml
从System.Windows.Markup.XamlReader.Load()
文件加载该资源,则特殊字符将替换为string.Empty
,如:
NewLine
代替New
Line
或New + Environment.NewLine + Line
。这是我加载资源的方式:
using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
{
//I just realized that I could simply use the Source
//property without using the Load method. But the same thing happens.
var dictionary = (ResourceDictionary)System.Windows.Markup.XamlReader.Load(fs, new ParserContext { XmlSpace = "preserve" });
dictionary.Source = new Uri(Path.GetFullPath(file), UriKind.Absolute);
var test = dictionary["Example.Line"] as string;
}
有没有办法避免XamlReader
替换特殊字符代码?
使用此代码转义特殊字符:
//Replaces the special chars.
var text = File.ReadAllText(file, Encoding.UTF8).Replace("&#", "&#");
File.WriteAllText(file, text, Encoding.UTF8);
var dictionary = new ResourceDictionary { Source = new Uri(Path.GetFullPath(file), UriKind.Absolute) };
我能够加载ResourceDictionary
而不会丢失新的行值。不过,我不相信这是最好的方式。 :/
答案 0 :(得分:0)
您可以将ParserContext
参数用于XamlReader.Load:
XamlReader.Load(xaml, new ParserContext() { XmlSpace = "preserve" });
更多信息:https://msdn.microsoft.com/en-us/library/ms590393(v=vs.110).aspx