This question is similar to How to add a Column ContextMenu in the WPF DataGrid, but what I am trying to do is add a different ContextMenu
PER COLUMN in the WPF Datagrid.
DataGridTextColumn
is not derived from FrameworkElement
which has a ContextMenu
property, so it is not possible to set a ContextMenu
directly on a DataGridTextColumn
. DataGridCell
also has a ContextMenu
, but I don't see how to use that for setting a column-specific menu.
The question here is how to add a unique ContextMenu
for each column (columns are dynamically generated).
Thanks!
Here is an example of how this can be achieved when setting the columns up explicitly:
<DataGrid ItemsSource="{Binding MyItems}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Column1Data}" HorizontalAlignment="Stretch">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Col 1 Item 1"/>
<MenuItem Header="Col 1 Item 2"/>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Column2Data}" HorizontalAlignment="Stretch" >
<CheckBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Col 2 Item 1"/>
<MenuItem Header="Col 2 Item 2"/>
</ContextMenu>
</CheckBox.ContextMenu>
</CheckBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
This example includes a Text
column and a CheckBox
column. You could modify the CellTemplate
to suit your requirements, and of course use resources to avoid code duplication.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With