Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a ContextMenu per column in the WPF data grid

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!

like image 926
edtheprogrammerguy Avatar asked Jul 23 '13 14:07

edtheprogrammerguy


1 Answers

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.

like image 187
Richard E Avatar answered Sep 28 '22 05:09

Richard E