Can you have submenus with the top level set to checkable in WPF? I can’t seem to get this to work.
<Window.ContextMenu>
<ContextMenu>
<MenuItem Header="Top Level 1" IsCheckable="True" IsChecked="True">
<MenuItem Header="Sub Level" />
<MenuItem Header="Sub Level" />
</MenuItem>
<MenuItem Header="Top Level 2">
<MenuItem Header="Sub Level" />
<MenuItem Header="Sub Level" />
</MenuItem>
</ContextMenu>
</Window.ContextMenu>
Top Level 1 is checkable, but the sub levels don’t appear. Any thoughts?
If you dig into
MenuItem‘sControlTemplate, you will see that it uses different templates depending on it’sRoleproperty.Reference:
Menu Styles and Templates
Seems like it can either allow checking or subitems by default.
To workaround that, use following code:
XAML:
Code behind:
I strongly recommend converting/encapsulating this piece of functionality into an
Attached Propertyor aBehavior.