Search code examples
c#wpfhierarchyresourcedictionary

Merged Resource Dictionaries of Windows does not reflect on child controls


Resource dictionary merged to the Window as given in the code below.

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="DefaultTheme.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>

I had created a custom control for context menu and had created the corresponding style in the DefaultTheme.xaml file. Even though at the window level it had the resource dictionary merged, the styles were not accessible for the custom controls.

Since it was custom control I had to merge the dictionary in the C# constructor like this -

const string defaultThemePath = "DefaultTheme.xaml";
var dictionary = new ResourceDictionary { Source = new Uri(defaultThemePath, UriKind.Relative) };
Resources.MergedDictionaries.Add(dictionary);

If the resource dictionary is merged, it should be available for child controls is an expectation. Is my understanding wrong about merged resource dictionary?

Edit

As @Rohit Vats has rightly pointed, my custom control is context menu and it is not part of the visual child of the window. Hence it does not have the resource dictionary inherited.


Solution

  • I just quickly check by putting one SolidColorBrush in random ResourceDictionary and merge it under App resources and use that resource from ContextMenu and ContextMenu was able to access the resource.

    From MSDN, StaticResource lookup behaviour works like this:

    1. The lookup process checks for the requested key within the resource dictionary defined by the element that sets the property.

    2. The lookup process then traverses the logical tree upward, to the parent element and its resource dictionary. This continues until the root element is reached.

    3. Next, application resources are checked. Application resources are those resources within the resource dictionary that is defined by the Application object for your WPF application.

    As evident from the above assertion, it looks for logical parent and not Visual parent and in case resource is not found anywhere, it looks for resource under App resources.

    So, your case for ContextMenu will work if you merge resources under App resources.