Search code examples
wpfdictionarydllcustom-controlsresourcedictionary

How to use resource dictionaries in custom control library?


I've created a resource dictionary with some frequently used brushes.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <SolidColorBrush x:Key="GrayColor1" Color="#f2f2f2"/>
    <SolidColorBrush x:Key="GrayColor2" Color="#e5e5e5"/>
    <SolidColorBrush x:Key="GrayColor3" Color="#d9d9d9"/>
    ...
</ResourceDictionary>

I want to use them in many controls in the custom control library, but I didn't find any way to make them available to the controls.
In a normal app I will put them in App.xaml, but in a library there is no App.xaml file.
So what is the way to use resource dictionary in a library?

I already tried without success to merge the dictionary into /Themes/Generic.xaml as this:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/MyControls;component/DefaultBrushes.xaml"/>
        <ResourceDictionary Source="/MyControls;component/Styles/CustButton.xaml"/>
        <ResourceDictionary Source="/MyControls;component/Styles/CustTextBox.xaml"/>
        ...
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

But referencing the resources results in a null reference (seems that in Generic.xaml can be merged only control templates).


Solution

  • You have to merge them in each control, or in the most top control if you have nested controls.

    <UserControl.Resources>
       <ResourceDictionary>
           <ResourceDictionary.MergedDictionaries>
               <ResourceDictionary Source="pack://Application:,,,/MyControls;component/Styles/CusTextBox.xaml"/>
           </ResourceDictionary.MergedDictionaries>
       </ResourceDictionary>
    </UserControl.Resources>