Question

I have a WPF Window:

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

I have a resource dictionary in MyResourceDictionary.xaml:

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

But when I try to reference ChildStyle from MyUI.Window:

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

It tells me that it can't find FatherStyle. I read here and merged the dictionary in MyResourceDictionary.xaml:

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

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

Now it tells me it can't find ChildStyle. How do I reference this properly?

Was it helpful?

Solution

You can't reference a resource dictionary contained in a Window-type XAML file, from another file. What you need to do is create a separate resource dictionary, "Shared.xaml" or whatever:

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

Now reference the shared one from your main window:

... and also from "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>

And now in your "MyUI.xaml" window, you should be able to access the "ChildStyle" as you expected, by referencing "MyResourceDictionary":

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

    <s:SurfaceListBox Style="{StaticResource ResourceKey=ChildStyle}" />
</ResourceDictionary>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top