I have the following xaml:
Because MenuItem
is the container type and when it translates your view model into visual item it will wrap your template in MenuItem
. In the same way ListBox
will create ListBoxItem
or ListView
will use ListViewItem
. To bind properties of the wrapper you need to use ItemContainerStyle
<ContextMenu ItemsSource="{Binding TestItems}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="IsChecked" Value="{Binding IsSelected}"/>
<Setter Property="Header" Value="{Binding Header}"/>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
or, if you prefer, you can do it partially with ItemTemplate
and ItemContainerStyle
<ContextMenu ItemsSource="{Binding TestItems}">
<ContextMenu.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Header}"/>
</DataTemplate>
</ContextMenu.ItemTemplate>
<ContextMenu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="IsChecked" Value="{Binding IsSelected}"/>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
In this scenario whatever is in ItemTemplate
will become MenuItem.Header
but IsChecked
property still needs to be bound in ItemContainerStyle