mike01010
mike01010

Reputation: 6088

WPF/Xaml ContextMenu ItemContainerStyle behavior

The DataContext for my window is an IDictionary>.

Can anyone explain to me why this works fine:

<Style x:Key="MenuItemStyle">
    <Setter Property="MenuItem.Header" Value="{Binding Ticker}"/>
</Style>
<Style x:Key="ContextMenuStyle">
    <Setter Property="MenuItem.Header" Value="{Binding Key}"/>
    <Setter Property="MenuItem.ItemsSource" Value="{Binding Value}"/>
    <Setter Property="MenuItem.ItemContainerStyle" Value="{StaticResource MenuItemStyle}"/>
</Style>
<ContextMenu ItemContainerStyle="{StaticResource ContextMenuStyle}" ItemsSource="{Binding Quotes}" />

But this does not:

<Style TargetType="{x:Type ContextMenu}" x:Key="ContextMenuStyle">
    <Setter Property="MenuItem.Header" Value="{Binding Key}"/>
    <Setter Property="MenuItem.ItemsSource" Value="{Binding Value}"/>
    <Setter Property="MenuItem.ItemContainerStyle">
        <Setter.Value>
            <Style TargetType="{x:Type MenuItem}">
                <Setter Property="Header" Value="{Binding Ticker}"/>
            </Style>
        </Setter.Value>
    </Setter>
</Style>
<ContextMenu ItemContainerStyle="{StaticResource ContextMenuStyle}" ItemsSource="{Binding Quotes}" />

EDIT: if i remove T'argetType="{x:Type ContextMenu}"', it works fine. i don't clearly understand why however.

thanks

Upvotes: 2

Views: 5764

Answers (1)

Guillaume
Guillaume

Reputation: 1802

You need to change the value of the TargetType from ContextMenu to MenuItem. The ItemContainerStyle property of the ContextMenu sets the style to the container element of your ContextMenu, in this case a MenuItem. However you set the target type of the style to ContextMenu so it cannot work. See this link for more details.

Upvotes: 2

Related Questions