我正在为 WPF 应用程序制作一个主题编辑器。我动态生成 XAML 文件,然后将它们编译到应用程序使用的 DLL 中。用于生成 XAML 文件的代码遵循以下原则:
var dictionary = new ResourceDictionary();
...
dictionary.Add(key, new BitmapImage { UriSource = new Uri(relativePath, UriKind.Relative) });
...
XamlWriter.Save(dictionary, "myDictionary.xaml");
我的问题是 XamlWriter.Save
还序列化 BaseUri
属性:
<BitmapImage BaseUri="{x:Null}" UriSource="Images\myImage.png" x:Key="myImage" />
结果是,当应用程序尝试获取此图像时,它找不到它,因为 BaseUri
未设置。通常,XAML 解析器会设置此属性(通过 IUriContext 接口(interface)),但当它已在 XAML 中显式设置时,解析器不会设置它,因此它保持为 null。
是否有办法阻止 XamlWriter
序列化 BaseUri
属性?
如果我要序列化自定义类,我可以添加一个 ShouldSerializeBaseUri()
方法,或显式实现 IUriContext
(我尝试了这两个选项,它们给出了所需的结果) ,但是如何为 BitmapImage
做到这一点?
作为最后的手段,我可以加载 XAML 文件并使用 Linq to XML 删除属性,但我希望有一个更干净的解决方案。
最佳答案
如果我们不阻止 XamlWriter
写入 BaseUri
属性,而是为其提供不影响图像加载的内容,会怎么样?例如下面的代码:
<Image>
<Image.Source>
<BitmapImage UriSource="Resources/photo.JPG"/>
</Image.Source>
</Image>
似乎相当于
<Image>
<Image.Source>
<BitmapImage BaseUri="pack://application:,," UriSource="Resources/photo.JPG"/>
</Image.Source>
</Image>
尝试
dictionary.Add("Image", new BitmapImage{
BaseUri=new Uri("pack://application:,,"),
UriSource = new Uri(@"Images\myImage.png", UriKind.Relative)
});
如果您尝试将图像源设置为通过代码以这种方式创建的 BitmapImage - 它不会工作。但是 XamlWriter.Save()
生成的 XAML 在 XAML 时确实可以工作:)。好吧,我希望值得一试。
关于.net - 如何防止 XamlWriter.Save 序列化 BaseUri 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6495253/