.net - 如何防止 XamlWriter.Save 序列化 BaseUri 属性?

标签 .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");

我的问题是 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/

相关文章:

c# - 不允许派生类的具体属性实现接口(interface)的接口(interface)属性背后的原因是什么?

c# - TwoWay 绑定(bind)一个实现 INotifyPropertyChanged 的​​类,没有任何反应

c# - 在 MVVM WPF 应用程序中的 View 模型之间传递应用程序状态

wpf - 暂停对绑定(bind) ObservableCollection<T> 的 DataGrid 的更新

c# - 如何创建其他窗口继承的窗口?

c# - 如何在 XAML 中处理 "float"图像 (Windows 8 Metro)

java - iis 8 java 和 .net 网络服务

c# - C# 的 OPC 示例应用程序

c# - 文件流写入文件并读取 bfile

c# - XAML ListView ItemContainer 高度