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

标签 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中的这些文件,则一切正常。为了使其正常工作,我必须将这些StaticResource更改为DynamicResource。您知道为什么这不再起作用了吗?

谢谢 :-)

最佳答案

通过将词典移出App.xaml,在加载MyFirstTemplates.xaml时,每个词典的资源都不会位于另一个词典的资源树中。原始设置首先加载ColorsDictionary,然后在加载时通​​过App资源将其提供给ControlsTemplatesDictionary。在您的新设置中,为了使颜色资源在App资源中可用,需要通过MyFirstTemplates加载该颜色资源,这又需要加载这两个字典,而这又需要访问该颜色资源...因此有点不能静态解析的引用的无限循环。 DynamicResource可以等到所有内容加载完毕后再访问颜色而不会出现问题。

要解决此问题,请使用“动态”或将ColorsDictionary直接合并到ControlsTemplatesDictionary中。

关于wpf - 合并字典中共享的静态资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4325015/

相关文章:

tfs - 我的 TFS 没有提示合并/代码差异,只是覆盖?有TFS设置吗?

c# - 使用循环从字典中删除值

python - 将列表值分配给字典

c# - DataObject.GetDatapresent 与子类

WPF - 如何摆脱错误的设计时错误

java - 如何通过svn在eclipse中合并两个或多个java项目

mysql - 如何最好地合并四个大表

python - Python 中的哈希表

wpf - ScrollViewer.MeasureOverride 将 ComputerScrollbarVisibility 设置为 Collapsed,然后再将其设置为正确的值

wpf - 为 ListView 列设置不同的对齐方式