jingkecn/blog

How To: Share Resource Dictionaries in .Net Libraries

jingkecn opened this issue · 0 comments

Problematic

In .Net development,resource dictionaries are a common way to define objects that we expect to use more than once, such as strings, styles, sizes, etc.
And it is no secret that resources defined in App.xaml of the startup project are shared for all assemblies.
However, when referring to a resource in non-startup project, Visual Studio does not manage to do code navigation and will launch a Resource '*' is not found warning at design time, even if it will work at runtime after deployment, it is not quite practical without the ability of code navigation.

Solution

What Microsoft does not tell us is that an App.xaml of the local library project can be used for design time.
So we just have to add an App.xaml into the library project, and merge the common resource dictionaries in this file as we do for the startup project:

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
  <Application.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
        <!-- Libraries -->
        <ResourceDictionary Source="ms-appx:///${COMMON_ASSEMBLY_NAME}/${PATH_TO_RESOURCE}.xaml" />
        <!-- Other merged dictionaries here -->
      </ResourceDictionary.MergedDictionaries>
      <!-- Other app resources here -->
    </ResourceDictionary>
  </Application.Resources>
</Application>

Where:

  • ${COMMON_ASSEMBLY_NAME} is the common library where to put the shared resources.
  • ${PATH_TO_RESOURCE} is an unified access of the shared resources.
+ solution
  + resource.common.lib
    + resource.entry.xaml
  + lib.refer.to.common.resource
    + app.xaml
...