合并字典中共享的静态资源

时间:2010-12-01 13:51:26

标签: wpf merge dictionary staticresource

我目前正在制作可以动态应用于我的应用程序的样式和模板字典。在这个“新想要的”动态行为之前,我有几个资源字典,每个样式控件一个,我在App.xaml中合并:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="ColorsDictionary.xaml"/>
            <ResourceDictionary Source="ControlsTemplatesDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

现在,我希望我的应用程序可以设置样式,所以我决定将以前的所有资源合并到一个名为“MyFirstTemplates”的新资源中,并将此字典添加到App.xaml。

新词典“MyFirstTemplates.xaml”:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">"
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="ColorsDictionary.xaml"/>
        <ResourceDictionary Source="ControlsTemplatesDictionary.xaml"/>
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

新App.xaml:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="MyFirstTemplates.xaml"/>
        </ResourceDictionary.MergedDictionaries>
        <Style TargetType="{x:Type Window}"/>
    </ResourceDictionary>
</Application.Resources>

注意: Window 的默认样式是更正WPF 4的错误,请参阅Adding a Merged Dictionary to a Merged Dictionary

现在我已经进行了此更改,我不能再将“ColorsDictionary.xaml”中的颜色资源用作“ControlsTemplateDictionary.xaml”中的 StaticResource 。如果我改回到在app.xaml中合并这些文件,一切正常。为了使其工作,我必须为 DynamicResource 更改这些 StaticResource 。你知道为什么它不再起作用吗?

谢谢: - )

2 个答案:

答案 0 :(得分:9)

通过将字典移出App.xaml,在加载MyFirstTemplates.xaml期间,每个字典中的资源不在另一个字典中。您的原始设置首先加载了ColorsDictionary,然后在加载时通​​过App资源提供给ControlsTemplatesDictionary。在你的新设置中,为了使颜色资源在App资源中可用,它需要通过MyFirstTemplates加载,这反过来又需要加载两个字典,这反过来需要访问颜色资源...所以它的类型无限循环的引用,无法静态解析。 DynamicResource可以等到所有内容都加载完毕后再访问颜色。

要修复使用Dynamic或将ColorsDictionary直接合并到ControlsTemplatesDictionary。

答案 1 :(得分:2)

John解释为什么会这样。 所以问题是当在合并字典中使用合并字典时,内部字典不能使用&#34;使用&#34;彼此为StaticResource。

基本解决方案:

  • 使用 DynamicResource
  • 使用 StaticResource
  • 时,只使用App.xaml中的单层次层次结构

这两种解决方案都存在问题。 DynamicResource存在性能问题。第二种解决方案限制了您组织XAML资源的方式。

替代解决方案:

我创建了一个小的简单程序(在GitHub中提供),它将作为预构建事件运行,并将文件夹中的XAML文件合并到一个长.XAML文件中。好吧,他们需要使用不同的扩展名(.txaml),否则他们将被编译。

这允许根据需要构建资源文件夹和文件,而不受WPF的限制。 StaticResource和设计师将一直工作。

The code in GitHub包含一个包含合并程序的简单解决方案。它将2个文件夹合并为2个文件。一个用于App.xaml资源,另一个用于Generic.xaml资源。 &#34;控件&#34;中的.xaml文件项目(还有&#34; Main&#34;项目)。

Blog post explaining this

相关问题