Using a global ResourceDictionary in a UserControl Library without referencing it in the UserControl

51 Views Asked by At

I have created a WPF Class Library project containing several UserControls. My intention is to establish common styles, templates, and resources that all UserControls within the library can utilize and reference.

I attempted to define a ResourceDictionary at the assembly level, specifically in Themes/Generic.xaml. However, it seems that the resources defined in this manner cannot be located when attempting to use them within the UserControls.

For example, in Themes/Generic.xaml:

<ResourceDictionary 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <SolidColorBrush x:Key="TextColorBrush" Color="Blue"/>
</ResourceDictionary>

Then in one of the UserControls:

<UserControl
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">

  <TextBlock Text="Hello" Foreground="{StaticResource TextColorBrush}"/>

</UserControl>

This will result in a compile-time error, as the resource cannot be resolved without an explicit reference to the Global ResourceDictionary.

Is there a way to define the global resources so they are implicitly available throughout the entire assembly/project without needing to include the ResourceDictionary in every UserControl?

Ideally, I don't want every control to have to contain:

<UserControl.Resources>
  <ResourceDictionary Source="Themes/Generic.xaml"/>
</UserControl.Resources>

Any suggestions would be appreciated!

1

There are 1 best solutions below

1
JonasH On

You can put resources in your app.xaml file:

    <Application.Resources>
         <ResourceDictionary>
             <ResourceDictionary.MergedDictionaries>
                 <!-- Merged dictionaries -->
            </ResourceDictionary.MergedDictionaries>
            <!-- Other resources -->
          </ResourceDictionary>
    </Application.Resources>

This should make the resources available for all controls in the same application.

If you are writing a library you could just put all resources in a common resource dictionary, and then just include this in each control you write. You still need to include it, but it would at least be fairly little code to include.

But I have no idea what the best way to handle styles when writing libraries is. I would like it if the application had some nice way to override styles if it wants to deviate from the defaults. I have not been able to find any clear guidance on how how to best manage styles and other resources when writing libraries.