Search code examples
wpfxamlresourcedictionary

Multiple ResourceDictionary with same DataTemplate key?


I have a ResourceDictionary such as (MyResourceDictionary):

<ResourceDictionary xmlns
        .....
        >

        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="SeriesTwo.xaml" />
        </ResourceDictionary.MergedDictionaries>

        <DataTemplate x:Key="SeriesDetailedInformation">
            <StackPanel>
                ......content...
            </StackPanel>
        </DataTemplate>
</ResourceDictionary>

SeriesTwo.xaml looks like this and also has the DataTemplate with the same name

<ResourceDictionary xmlns=
        .....
        >
        <DataTemplate x:Key="SeriesDetailedInformation">
            <DataGrid>
                ......content...
            </DataGrid>
        </DataTemplate>
</ResourceDictionary>

On my view page, which SeriesDetailedInformation data template gets used? Does it depend on which resource dictionary I reference first on my page?

Any good links and other reading material regarding this topic is also appreciated.


Solution

  • A couple of things from this page seem relevant to your question:

    Lookup behavior within the MergedDictionaries collection searches the last-added ResourceDictionary first, and the search stops as soon as a requested key is found. In other words, the retrieval logic from the collection of merged resource dictionaries is last in, first out.

    And:

    Resources in a merged dictionary occupy a location in the resource lookup scope that is just after the scope of the main resource dictionary they are merged into.

    From this I gather that the DataTemplate defined in your main dictionary would be used first, then SeriesTwo, and any referenced before/above SeriesTwo after that.

    Also, why not just try it out and see what happens? I maintain a solution I call "DumbCrapTestApp" where I test stuff like this when I'm curious about how something works. It has a console app for when I just need to test something within the language, and a WPF and a Silverlight app for when I want to try something there. If I needed a WinForms app, I'd just add one and do my thing there. I simply put whatever code I want to test into the relevant app, set it as my Startup Project, and away I go. It's really useful for figuring out these little things and I've even used it to get clarification and verify answers before I post them here on SO.