How to make a WPF style inheritable to derived classes?

If you have a Style defined in your application like so:

<Style TargetType="{x:Type ContextMenu}" ...

Then that is an implicit Style, not a default Style. Default Styles are generally located in the same assembly as the control or in matching assemblies (i.e. MyAssembly.Aero.dll).

Implicit Styles are not automatically applied to derived types, which is probably what you are seeing.

You can either define a second Style, like so:

<Style x:Key="{x:Type ContextMenu}" TargetType="{x:Type ContextMenu}" ...
<Style TargetType="{x:Type local:MyContextMenu}" BasedOn="{StaticResource {x:Type ContextMenu}}" ...

Or you can leverage the Style property of your control. You could do the following from XAML

<local:MyContextMenu Style="{DynamicResource {x:Type ContextMenu}}" ...

or you can do this in your MyContextMenu like so:

public MyContextMenu() {
    this.SetResourceReference(StyleProperty, typeof(ContextMenu));
}

Tags:

C#

Wpf

Xaml