Styles from generic.xaml are not applied Styles from generic.xaml are not applied wpf wpf

Styles from generic.xaml are not applied


You need the following line in your custom control constructor:

public class MyCustomControl : Control{    static MyCustomControl()    {        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));    }}

Then if you have a generic.xaml file inside themes folder, with the following sample style:

<Style TargetType="{x:Type local:MyCustomControl}">    <Setter Property="Template">        <Setter.Value>            <ControlTemplate TargetType="{x:Type local:MyCustomControl}">                <Border>                    <Label>Testing...</Label>                </Border>            </ControlTemplate>        </Setter.Value>    </Setter></Style>

Now the style will get automatically applied without any extra merging.


To apply default styles in Themes\Generic.xaml in my custom controls library I decided to seek inspiration from a well established open source controls library (MahApps). This project gives you a really good example of how to structure and layout a custom controls library.

Cut a long story short, to get your default styles in Themes\Generic.xaml you need to include the following in the AssemblyInfo.cs file in your custom controls library:

[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]

In my case, my custom controls AssemblyInfo.cs looked something like:

using System.Runtime.InteropServices;using System.Windows;using System.Windows.Markup;[assembly: AssemblyCopyright("...")][assembly: ComVisible(false)][assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)][assembly: AssemblyVersion("1.0.0.0")][assembly: AssemblyFileVersion("1.0.0.0")][assembly: AssemblyInformationalVersion("1.0.0.0")][assembly: AssemblyTitleAttribute("...")][assembly: AssemblyDescriptionAttribute("")][assembly: AssemblyProductAttribute("...")][assembly: AssemblyCompany("...")]


Not sure if this works in WPF, but it works for me in Silverlight:

Constructor:

public class MyCustomControl : Control{    static MyCustomControl()    {        this.Style = (Style)Application.Current.Resources["MyCustomControlStyle"];    }}

Style:

<Style x:Key="MyCustomControlStyle" TargetType="{local:MyCustomControl}">    <Setter Property="Template">        <Setter.Value>            <ControlTemplate TargetType="{local:MyCustomControl}">                <Border>                    <Label>Testing...</Label>                </Border>            </ControlTemplate>        </Setter.Value>    </Setter></Style>