How to make a WPF style inheritable to derived classes?

Viewed 5173

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.

2 Answers

In complement to CodeNaked's excellent suggestions, I tried specifying Style in the XAML part of MyContextMenu:

<ContextMenu x:Class=LocalProject.MyContextMenu"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:AdelSoft_WS_FRA_Test.Composants"
             mc:Ignorable="d"
             Style="{DynamicResource {x:Type ContextMenu}}">

The compiler warned me that it cannot resolve the resource, but at runtime it looks quite able to.

Naturally, you can also use

             Style="{StaticResource ContextMenuStyleName}">

if you use style names.

Related