I am adding a context menu to cells like this
<ContextMenu x:Key="cellContextMenu"> <MenuItem x:Name="menuFillUp" Click="menuFillUp_Click" Header="Fill _Up" /> <MenuItem x:Name="menuFillDown" Click="menuFillDown_Click" Header="Fill _Down" /> </ContextMenu>
and set it like this
<Style TargetType="{x:Type dg:DataGridCell}"> <Setter Property="ContextMenu" Value="{DynamicResource cellContextMenu}" /> </Style>
then I add the context menu to the column header using the following context menu
<DataTemplate x:Key="menuItemColumnShow"> <MenuItem x:Name="menuShowColumn" DataContext="{Binding Path=.}" Header="{Binding Path=Tag.Code}" Click="menuShowColumn_Click" /> </DataTemplate> <ContextMenu x:Key="columnContextMenu"> <MenuItem x:Name="menuHideColumn" Click="menuHideColumn_Click" Header="Hide _Column" /> <MenuItem x:Name="showMenu" Header="Show" ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:ResultEditorGrid}}, Path=HiddenColumnCollection}" ItemTemplate="{StaticResource menuItemColumnShow}"> <MenuItem.Style> <Style BasedOn="{StaticResource {x:Type MenuItem}}" TargetType="{x:Type MenuItem}"> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource self}, Path=Items.Count}" Value="0"> <Setter Property="Visibility" Value="Collapsed" /> </DataTrigger> </Style.Triggers> </Style> </MenuItem.Style> </MenuItem> <MenuItem Header="_Add Item" Command="local:MyCommands.AddTItem" CommandTarget="{Binding Path=PlacementTarget, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}" /> </ContextMenu> <Style TargetType="{x:Type dg:DataGridColumnHeader}"> <Setter Property="ContextMenu" Value="{DynamicResource columnContextMenu}" /> </Style>
(im, using wierd mix of commands and click events, the type of code evolves :) that the above code gives me dynamic menus in the column headers. I have a hidden collection of columns on my derived grid, and I show that the shich columns are hidden / shown in the context menu in the column, and I have a separate context menu for the cells in the grid.
you can find which column was clicked
private void menuHideColumn_Click(object sender, RoutedEventArgs e) {
I may have missed a few things, feel free to comment and poorly try to fill in the details.
source share