Question

I would like to restyle a ContextMenu, but I have a question about how to structure my Xaml.

In my application resources, I have something like this:

<ControlTemplate TargetType="MenuItem" x:Key="MenuItemTemplate">
    ...
</ControlTemplate>

<ControlTemplate TargetType="ContextMenu" x:Key="ContextMenuTemplate">
    <ControlTemplate.Resources>
        <Style TargetType="{x:Type MenuItem}">
            <Setter Property="Template" Value="{StaticResource MenuItemTemplate}" />
        </Style>
    </ControlTemplate.Resources>

    ...    

</ControlTemplate>

<Style TargetType="{x:Type ContextMenu}" x:Key="RadialContextMenu">
    <Setter Property="Template" Value="{StaticResource ContextMenuTemplate}" />
</Style>

This seems to work fine, context menus with the ContextMenuTemplate style have styled menu items, and other context menus are unaffected, without having to set a style explicitly on any MenuItems.

<ContextMenu x:Name="menu" Style="{StaticResource RadialContextMenu}">
    <MenuItem Header="Foo"/>
    <MenuItem Header="Bar"/>
</ContextMenu>

However, I don't like having that ControlTemplate.Resources section. I'd much rather have it for example inside the x:Key="RadialContextMenu" style, so that both of the control templates are "clean".

How can I move the Style element out of the second ControlTemplate?

Was it helpful?

Solution

Try this:

<Style TargetType="{x:Type ContextMenu}" x:Key="RadialContextMenu">
    <Setter Property="ItemContainerStyle">
        <Setter.Value>
            <Style TargetType="{x:Type MenuItem}">
                <Setter Property="Template" Value="{StaticResource MenuItemTemplate}" />
            </Style>
        </Setter.Value>
    </Setter>
</Style>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top