如何在WPF中将一个ResourceDictionary导入到其他资源中?

sns*_*uff 21 .net c# wpf xaml resourcedictionary

是否可以将一个资源字典添加到另一个资源字典中?谢谢你的帮助.

Til*_*lak 21

在Dictionary2.xaml中定义MergedDictionaries(在打开ResourceDictionary标记之后):

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="/Path/to/Dictionary1.xaml" />
</ResourceDictionary.MergedDictionaries>
Run Code Online (Sandbox Code Playgroud)

有一个问题:每次合并字典时,您都可以有效地创建合并字典的副本.并且它是递归的 - 如果您有Dict3.xaml和Dict4.xaml都加载Dictionary2.xaml,您将创建三个Dictionary1.xaml实例

解决方案是SharedResourceDictionary.本教程中的实现应视为一个起点,可能需要进行一定程度的调整 - 具体取决于使用场景.谷歌"wpf SharedResourceDictionary"的一些陷阱和解决方案.

从回答这个问题XAMeLi


Sco*_*ott 6

直接来自我正在处理的 sketchflow 项目的片段,展示了如何在 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>
Run Code Online (Sandbox Code Playgroud)

这显示了将两个附加资源字典合并到另一个资源字典中。

(请注意,如果您在多个位置定义了默认样式,则顺序可能会变得很重要,因为它们会相互覆盖)