Search code examples
wpfwpf-style

How can I have generic.xaml from class library be used with TargetType only?


I created a WPF class library containing themes which I want to refer to and use in two WPF applications.

This is an example content, taken from my \Themes\generic.xaml file in the class library:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
  <Style TargetType="Border">
    <Setter Property="Background">
      <Setter.Value>
        <SolidColorBrush Color="Tan"/>
      </Setter.Value>
    </Setter>
  </Style>
</ResourceDictionary>

And this is the AssemblyInfo.cs file I added to the class library:

using System.Windows;

[assembly: ThemeInfo(
    ResourceDictionaryLocation.SourceAssembly,  //where theme specific resource dictionaries are located
                                                //(used if a resource is not found in the page,
                                                // or application resource dictionaries)
    ResourceDictionaryLocation.SourceAssembly   //where the generic resource dictionary is located
                                                //(used if a resource is not found in the page,
                                                // app, or any theme specific resource dictionaries)
)]

Nevertheless, my WPF application doesn't use the styles I've defined in the class library.

What am I missing? Why are the styles from my class library not used by my WPF application although the class library project is referenced by my WPF application?


Solution

  • The Themes/generic.xaml naming convention is (only) used to lookup the default style(s) for any controls that are defined in the source assembly (or a specific theme assembly depending on the [ThemeInfo] attribute).

    It's not used to apply styles to other controls or elements such as Border, which is defined in PresentationFramework.dll.

    So to apply your Style to Border elements in your app, you need to merge the resource dictionary in your App.xaml:

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Themes/generic.xaml.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>