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

时间:2014-02-17 05:30:39

标签: c# wpf xaml resourcedictionary

我有一个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>

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

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

它告诉我它找不到FatherStyle。我读了here并合并了MyResourceDictionary.xaml中的字典:

<ResourceDictionary xmlns="........."
                    and so on >
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="MainWindow.xaml" />
    </ResourceDictionary.MergedDictionaries>

    <Style ChildStyle as shown above />
</ResourceDictionary>

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

1 个答案:

答案 0 :(得分:1)

您无法从其他文件引用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>