wpf – 将合并的词典添加到合并词典中

我似乎无法将合并的字典添加到XAML中的合并字典集合中。

Theme.xaml

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="/Mine;component/Themes/Palette.Blue.xaml"/>
    <ResourceDictionary Source="/Mine;component/Themes/Template.xaml"/>
</ResourceDictionary.MergedDictionaries>

应用资源

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Mine;component/Themes/Theme.xaml"/> 
            <!--
            <ResourceDictionary Source=="/Mine;component/Themes/Palette.Blue.xaml"/>
            <ResourceDictionary Source="/Mine;component/Themes/Template.xaml"/>
            -->
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

注意:如果我将两个ResourceDictionaries都放在Appication.Resources MergedDictionary中(注释掉了theme.xaml并取消了其他两个字典的注释),他们都正确地加载。然而,我们的资源定义的方式,这可能意味着将加载相当多的资源,对于动态加载,我想能够定义模板。

最佳答案
这是一个优化错误,请参阅this链接

On the creation of every object in
XAML, if a default style is present
(i.e. style w/ a key of Type) that
style should be applied. As you can
imagine there are several performance
optimizations to make that (implied)
lookup a light weight as possible. One
of them is that we don’t look inside
Resource Dictionaries unless they are
flagged as “containing default
Styles”. There is a bug: if all your
default styles are nested in merged
dictionaries three levels deep (or
deeper) the top dictionary does not
get flagged so the search skips it.
The work around is to put a default
Style to something, anything, in the root
Dictionary.

所以添加一个虚拟样式到根字典修复这个。例

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Mine;component/Themes/Theme.xaml"/>
        </ResourceDictionary.MergedDictionaries>
        <!-- Dummy Style, anything you won't use goes -->
        <Style TargetType="{x:Type Rectangle}" />
    </ResourceDictionary>
</Application.Resources>

转载注明原文:wpf – 将合并的词典添加到合并词典中 - 代码日志