wpf.net-4.0resourcedictionarymergeddictionaries

Nested Resource Dictionary in separate library


My question is very similar to this one

I have a solution with a number of projects. The are two that are relevant: a class library that contains a WPF window and a project with all the WPF styles in it.

Class Library with the window in Project 1

The Window's merged dictionary is something like:

  <ResourceDictionary.MergedDictionaries>
       <ResourceDictionary Source="pack://application:,,,/StyleAssembly;component/CommonStyle.xaml"/>
  </ResourceDictionary.MergedDictionaries> 

            //other styles here

The CommonStyle.xaml in Project 2:

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="/Components/Type/CheckBox.xaml"/>
</ResourceDictionary.MergedDictionaries>

That results in errors like:

{"Cannot locate resource 'components/type/checkbox.xaml'."}

However, if I create a CommonStyle.xaml in Project 1 and reference the same control styles from Project 2 then it works.

How do I make that highest level xaml file (CommonStyle.xaml) work from the Project 2?


Solution

  • I am currently unable to test this, however I hope it should work.

    Rather than a rooted path, use a relative path in Project 2, i.e.

    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Components/Type/CheckBox.xaml"/>
    </ResourceDictionary.MergedDictionaries>
    

    You may also use .. as required to navigate up to a relative directory (depending upon the location of CommonStyle.xaml), e.g.

    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="../Components/Type/CheckBox.xaml"/>
    </ResourceDictionary.MergedDictionaries>
    

    I believe when you use a rooted path (starting with /) it will look for CheckBox.xaml in the root of the project where you use CommonStyle.xaml rather than relative to the location of CommonStyle.xaml.

    Additional Explanation

    From you have described, it seems you have the following structure:

    - Project 1
      - Window.xaml
    - Project 2
      - CommonStyle.xaml
      - Components
        - Type
          - CheckBox.xaml
    

    When CommonStyle.xaml refers to / it is normally referring to the root of Project 2, however when you merge this into Window.xaml the / would now refer to the root of Project 1, subsequently it is unable to locate Components/Type/CheckBox.xaml.

    By removing the / it will now look for Components/Type/CheckBox.xaml relative to the location of CommonStyle.xaml which it is able to do.