dariusriggins
dariusriggins

Reputation: 1444

Setting style of ContextMenu on subitems

I have created a custom style and template for MenuItem and ContextMenu, and for my first level, that works great, but whenever I add a SubMenu item, the style of that ContextMenu reverts back to the default style. How can I make sure that item uses my custom style? I've tried using the <;Style TargetType="ContextMenu" Key="{x:Type ContextMenu}" syntax as well, and it doesn't seem to be overriding it either.

Upvotes: 1

Views: 2194

Answers (1)

Abe Heidebrecht
Abe Heidebrecht

Reputation: 30498

The problem is that the style is being applied to the ContextMenu's child menu items. Since they themselves are ItemsControls, the grandchildren are picking up the ItemContainerStyle from the MenuItem style. I would suggest pulling the MenuItem style out into a separate resource, and then using it like so:

<Style x:Key="menuItemStyle" TargetType="{x:Type MenuItem}">
   ...
</Style>

<Style TargetType="{x:Type ContextMenu}">
    <Setter Property="ItemContainerStyle">
        <Setter.Value>
            <Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource menuItemStyle}">
                <Setter Property="ItemContainerStyle" Value="{StaticResource menuItemStyle}" />
            </Style>
        </Setter.Value>
    </Setter>
</Style>

Upvotes: 2

Related Questions