如何将单击事件处理程序添加到 DataGrid 上下文菜单?

How can I add a Click Event Handler to a DataGrid Context Menu?

如何将单击事件处理程序添加到 DataGrid 的动态生成的上下文菜单?

我看到有人说使用 'Tag' 属性,但我不确定如何在 XAML 中添加代码,或者是否需要在代码隐藏中完成。

谢谢。

<DataGrid ItemsSource="{Binding MyModules}" AutoGenerateColumns="False" x:Name="dataGrid">

    <DataGrid.ItemContainerStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu ItemsSource="{Binding Configuration.Commands}">
                        <ContextMenu.ItemContainerStyle>
                            <Style TargetType="MenuItem">
                                <Setter Property="Header" Value="{Binding Caption}" />
                                <!-- Instead of the following two lines where I set the CommandAction and CommandParameter, I need to have a Click Event Handler. How can I achieve that? -->
                                <!-- <Setter Property="Command" Value="{Binding CommandAction}" />
                                <Setter Property="CommandParameter" Value="{Binding CommandId}" /> -->
                            </Style>
                        </ContextMenu.ItemContainerStyle>
                    </ContextMenu>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGrid.ItemContainerStyle>
    
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Module Name" Width="*" IsReadOnly="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Configuration.Name}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

        <DataGridTemplateColumn Header="Module Caption" Width="3*" IsReadOnly="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Configuration.Description}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>

</DataGrid>

您可以使用 EventSetter:

<Setter Property="ContextMenu">
    <Setter.Value>
        <ContextMenu ItemsSource="{Binding Configuration.Commands}">
            <ContextMenu.ItemContainerStyle>
                <Style TargetType="MenuItem">
                    <Setter Property="Header" Value="{Binding Caption}" />
                    <EventSetter Event="Click" Handler="MenuItem_Click" />
                </Style>
            </ContextMenu.ItemContainerStyle>
        </ContextMenu>
    </Setter.Value>
</Setter>