Tho*_*que 5 .net wpf xaml serialization xamlwriter
我正在为 WPF 应用程序制作主题编辑器。我动态生成 XAML 文件,然后将它们编译到应用程序使用的 DLL 中。用于生成 XAML 文件的代码遵循以下原则:
var dictionary = new ResourceDictionary();
...
dictionary.Add(key, new BitmapImage { UriSource = new Uri(relativePath, UriKind.Relative) });
...
XamlWriter.Save(dictionary, "myDictionary.xaml");
Run Code Online (Sandbox Code Playgroud)
我的问题是它XamlWriter.Save也序列化了BaseUri属性:
<BitmapImage BaseUri="{x:Null}" UriSource="Images\myImage.png" x:Key="myImage" />
Run Code Online (Sandbox Code Playgroud)
BaseUri结果是,当应用程序尝试获取该图像时,由于未设置而找不到它。通常,XAML 解析器设置此属性(通过IUriContext接口),但当它已在 XAML 中显式设置时,解析器不会设置它,因此它保持为 null。
有没有办法阻止XamlWriter序列化BaseUri属性?
如果我要序列化自定义类,我可以添加一个ShouldSerializeBaseUri()方法,或IUriContext显式实现(我尝试了这两个选项,它们给出了所需的结果),但如何做到这一点BitmapImage?
作为最后的手段,我可以加载 XAML 文件并使用 Linq to XML 删除属性,但我希望有一个更干净的解决方案。