Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a WPF style inheritable to derived classes?

Tags:

c#

wpf

xaml

In our WPF app we have a global style with TargetType={x:Type ContextMenu}. I have created a MyContextMenu that derives from ContextMenu, but now the default style does not apply.

How can I tell WPF that I want MyContextMenu to inherit the default style from ContextMenu? Hopefully I can do this from within my control itself (via static ctor metadata override or something?) and not have to mess around in any xaml.

like image 722
scobi Avatar asked Jul 21 '11 18:07

scobi


1 Answers

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));
}
like image 152
CodeNaked Avatar answered Nov 09 '22 19:11

CodeNaked