右键单击 Xceed 扩展 WPF 数据网格 select 行

Xceed extended WPF datagrid select row with right click

我正在尝试向 Xceed 扩展 WPF 数据网格添加上下文菜单。我能够显示上下文菜单并从菜单中触发命令,但右键单击一行不会将其设置为选定行,因此命令使用了错误的记录。

有没有办法改变选中项的设置方式,使其可以通过右键单击进行更新?

<xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource RecordsForList}}" SelectedItem="{Binding SelectedRecord}">
    <xcdg:DataGridControl.ContextMenu>
        <ContextMenu>
            <MenuItem Command="{Binding OpenCommand}" Header="Open" />
        </ContextMenu>
    </xcdg:DataGridControl.ContextMenu>
</xcdg:DataGridControl>

如果您为每个 DataRow 设置 ContextMenu 属性,则可以将当前项目作为命令参数传递给命令,而不是更改选择项目的方式:

<xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource RecordsForList}}" SelectedItem="{Binding SelectedRecord}">
    <xcdg:DataGridControl.ItemContainerStyle>
        <Style TargetType="xcdg:DataRow">
            <Setter Property="Tag" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType=xcdg:DataGridControl}}" />
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu>
                        <MenuItem Command="{Binding PlacementTarget.Tag.OpenCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
                                  CommandParameter="{Binding}" Header="Open" />
                    </ContextMenu>
                </Setter.Value>
            </Setter>
        </Style>
    </xcdg:DataGridControl.ItemContainerStyle>
</xcdg:DataGridControl>

另一种选择是在视图中编写一些代码,在右键单击时实际选择一个项目,例如:

<xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource RecordsForList}}"  SelectedItem="{Binding SelectedRecord}">
    <xcdg:DataGridControl.ContextMenu>
        <ContextMenu>
            <MenuItem Command="{Binding OpenCommand}" Header="Open" />
        </ContextMenu>
    </xcdg:DataGridControl.ContextMenu>
    <xcdg:DataGridControl.ItemContainerStyle>
        <Style TargetType="xcdg:DataRow">
            <EventSetter Event="PreviewMouseRightButtonDown" Handler="xgrid_PreviewMouseRightButtonDown" />
        </Style>
    </xcdg:DataGridControl.ItemContainerStyle>
</xcdg:DataGridControl>

private void xgrid_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    Xceed.Wpf.DataGrid.DataRow row = sender as Xceed.Wpf.DataGrid.DataRow;
    xgrid.CurrentItem = row.DataContext;
}