【问题标题】:How to prevent XamlWriter.Save from serializing the BaseUri property?如何防止 XamlWriter.Save 序列化 BaseUri 属性?
【发布时间】:2011-09-23 15:03:18
【问题描述】:

我正在为 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 接口),但是当它已经在 XAML 中显式设置时,解析器不会设置它,所以它保持为空。

有没有办法防止XamlWriter 序列化BaseUri 属性?

如果我正在序列化一个自定义类,我可以添加一个ShouldSerializeBaseUri() 方法,或者显式实现IUriContext(我尝试了这两个选项并且它们给出了想要的结果),但是对于BitmapImage,如何做到这一点呢?

作为最后的手段,我可​​以加载 XAML 文件并使用 Linq to XML 删除属性,但我希望有一个更简洁的解决方案。

【问题讨论】:

    标签: .net wpf xaml serialization xamlwriter


    【解决方案1】:

    如果不是阻止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 时确实有效 :)。好吧,我希望值得一试。

    【讨论】:

    • 感谢您的回答,这是一个有趣的想法......我会试试看
    【解决方案2】:

    我最终通过使用 Linq to XML 手动生成 XAML 解决了这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 2012-08-04
      相关资源
      最近更新 更多