How to import one ResourceDictionary into other, in WPF?

混江龙づ霸主 提交于 2020-01-12 06:25:07

问题


Is it possible to add one resource dictionary into other one? Thanks for any help.


回答1:


In Dictionary2.xaml define MergedDictionaries (right after the opening ResourceDictionary tag):

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="/Path/to/Dictionary1.xaml" />
</ResourceDictionary.MergedDictionaries>

there's a catch: each time you merge dictionaries you effectively create a copy of the merged dictionary. And it's recursive - if you have Dict3.xaml and Dict4.xaml that both load Dictionary2.xaml, you will have three instances of Dictionary1.xaml created

The solution is a SharedResourceDictionary. The implementation in the tutorial should be seen as a starting point and will probably need some level of tweaking - depending on use scenario. Google "wpf SharedResourceDictionary" for some gotchas and solutions.

From answer to this question by XAMeLi




回答2:


A snippet straight from a sketchflow project I am working on that shows how to merge resource dictionaries in xaml:

<Application.Resources>
    <!-- Resources scoped at the Application level should be defined here. -->
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Microsoft.Expression.Prototyping.SketchControls;component/ScrollViewerStyles.xaml"/>
            <ResourceDictionary Source="/[ProjectABC];component/[fileXYZ].xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

This shows merging two additional resource dictionaries into another resource dictionary.

(Note that the order can become important if you have default styles defined in more than one place as they will override each other)




回答3:


Something like:

ResourceDictionary resources = new ResourceDictionary();
resources.Source = new Uri("/MyModule;component/MyModule.xaml", 
     UriKind.RelativeOrAbsolute);
Application.Current.Resources.MergedDictionaries.Add(resources);

Might be what you're looking for. We use code like this in our Prism Modules.




回答4:


Without more context, it's difficult to give you a specific answer. Here's some possibly relevant resources on merging resource dictionaries:

http://msdn.microsoft.com/en-us/library/aa350178.aspx



来源:https://stackoverflow.com/questions/10541424/how-to-import-one-resourcedictionary-into-other-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!