I want to achieve a context menu behavior like e.g. visual studio has for toolbars, with a list of checkable items, and a list of commands. The contextmenu items should come from some observablecollection in view models.
As these come from different sources. I thought of using a composite collection to achieve this. Binding of one collection should be to Command, other to IsChecked/IsChecked. I also would like to use a separator.
The problem I have is about binding. I cannot use a datatemplate for complete menuitem because this does not include the IsChecked property. Therefore, I'm using ItemContainerStyle for it (see https://stackoverflow.com/a/29130774/5381620). As long as I only use 1 collection container and have 1 source everything is fine. However, inserting items from another source (or a Separator) will apply the "style" bindings to all menu items what is not intended and in case of 'Separator' will lead to an exception.
<ContextMenu>
<ContextMenu.Resources>
<CollectionViewSource x:Key="ContextMenuColCollection" Source="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path= DataContext.HeaderContextMenu}"/>
</ContextMenu.Resources>
<ContextMenu.ItemTemplate>
<DataTemplate DataType="{x:Type vm:Collection1VM}" >
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ContextMenu.ItemTemplate>
<ContextMenu.ItemsSource>
<CompositeCollection>
<MenuItem Header="Settings"/>
<Separator />
<CollectionContainer Collection="{Binding Source={StaticResource ContextMenuColCollection}}"/>
</CompositeCollection>
</ContextMenu.ItemsSource>
<ContextMenu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="IsCheckable" Value="True"/>
<Setter Property="IsChecked" Value="{Binding IsSelected}"/>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>