读取包含特殊字符的ResourceDictionary

时间:2017-02-28 03:18:44

标签: c# wpf

我有这个例子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: &#x0d;-->    
    <s:String x:Key="Example.Line">New&#x0d;Line</s:String>
</ResourceDictionary>

如果它已经在项目中并且我将其绑定到控件(例如TextBlock{DynamicBinding Example.Line},则一切都按预期工作。 (两个词在不同的行中)

现在,如果我使用.xamlSystem.Windows.Markup.XamlReader.Load()文件加载该资源,则特殊字符将替换为string.Empty,如:

  • NewLine代替New&#x0d;LineNew + 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("&#", "&amp;#");
File.WriteAllText(file, text, Encoding.UTF8);

var dictionary = new ResourceDictionary { Source = new Uri(Path.GetFullPath(file), UriKind.Absolute) }; 

我能够加载ResourceDictionary而不会丢失新的行值。不过,我不相信这是最好的方式。 :/

1 个答案:

答案 0 :(得分:0)

您可以将ParserContext参数用于XamlReader.Load:

XamlReader.Load(xaml, new ParserContext() { XmlSpace = "preserve" });

更多信息:https://msdn.microsoft.com/en-us/library/ms590393(v=vs.110).aspx

相关问题