从资源字典引用主窗口的字典



我有一个WPF窗口:

<Window x:Class="MyUI.MainWindow"
and so on>
<Window.Resources>
<ResourceDictionary>
<Style TargetType="{x:Type s:SurfaceListBox}" x:Key="FatherStyle" >
</ResourceDictionary>
</Window.Resources>
</Window>

我在MyResourceDictionary.xaml:中有一个资源字典

<ResourceDictionary xmlns="........."
and so on >
<Style TargetType="{x:Type s:SurfaceListBox}" x:Key="ChildStyle"  BasedOn="{StaticResource FatherStyle}" />
</ResourceDictionary>

但是当我尝试从MyUI.Window:引用ChildStyle

<Window as shown in 1st block of code above>
<s:SurfaceListBox Style="{StaticResource ResourceKey=ChildStyle}" />
</Window>

它告诉我它找不到FatherStyle。我在这里阅读并合并了MyResourceDictionary.xaml:中的词典

<ResourceDictionary xmlns="........."
and so on >
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="MainWindow.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style ChildStyle as shown above />
</ResourceDictionary>

现在它告诉我它找不到ChildStyle。我该如何正确引用它?

不能从其他文件引用包含在Window类型XAML文件中的资源字典。您需要做的是创建一个单独的资源字典,"Shared.xaml"或其他什么:

<ResourceDictionary ... >
<Style TargetType="{x:Type s:SurfaceListBox}" x:Key="FatherStyle" >
</ResourceDictionary>

现在从您的主窗口中引用共享的:

以及来自"MyResourceDictionary.xaml":

<ResourceDictionary xmlns="........."
and so on >
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Shared.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style TargetType="{x:Type s:SurfaceListBox}" x:Key="ChildStyle"  BasedOn="{StaticResource FatherStyle}" />
</ResourceDictionary>

现在,在您的"MyUI.xaml"窗口中,您应该能够通过引用"MyResourceDictionary"来访问您所期望的"ChildStyle":

<ResourceDictionary xmlns="........."
and so on >
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="MyResourceDictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
<s:SurfaceListBox Style="{StaticResource ResourceKey=ChildStyle}" />
</ResourceDictionary>

最新更新