如何在 WPF KeyBinding 中传递来自 DataGrid 的单元格信息?

How to Pass Cell Information from DataGrid in WPF KeyBinding?

我有一个 DataGrid 来列出 MobileInfo 集合。 DataGrid 配置为 SelectionUnit="FullRow"。如果我单击任何行,则它会选择整行,此外它还会指向鼠标被击中的带边框的单元格。边框选择在键盘导航时移动 例如:LeftRightUpDown。根据单元格选择,我希望传递有关单元格的信息。

参考具有输出屏幕的图像

在上面的屏幕截图中,Android 被选中,基于键盘导航,单元格选择被更改。

我的XAML源代码:

<DataGrid  AutoGenerateColumns="False" ItemsSource="{Binding MobileList, UpdateSourceTrigger=PropertyChanged}" SelectionUnit="FullRow" IsReadOnly="True">
    <DataGrid.InputBindings>
        <KeyBinding Key="C" Modifiers="Ctrl" Command="{Binding Path=DataContext.CopyToClipBoardCommand}" CommandParameter="{Binding }" />
    </DataGrid.InputBindings>
    <DataGrid.Columns>
        <!--Column 1-->
        <DataGridTextColumn Binding="{Binding MobileName}" Header="Name" />
        <!--Column 2-->
        <DataGridTextColumn Binding="{Binding MobileOS}" Header="OS" />
    </DataGrid.Columns>
</DataGrid>

Note: Don't Change the SelectionUnit in the DataGrid

请提供您的解决方案,如何基于键盘导航传递单元格信息

与 XAML DataGrid

关联的 C# 源代码
public class GridViewModel
{
    public ObservableCollection<MobileInfo> MobileList { get; set; }

    public GridViewModel()
    {
        MobileList = new ObservableCollection<MobileInfo>();
        MobileList.Add(new MobileInfo  { MobileName = "iPhone", MobileOS = "iOS" });
        MobileList.Add(new MobileInfo { MobileName = "Xperia", MobileOS = "Android" });
        MobileList.Add(new MobileInfo { MobileName = "Lumina", MobileOS = "Windows" });
    }

}

public class MobileInfo
{
    public string MobileName { get; set; }
    public string MobileOS { get; set; }
}

您可以将命令参数绑定到 DataGrid.CurrentCell 属性。有几种方法可以做到这一点,其中之一是指定绑定的相对来源:

<KeyBinding Key="C"
            Modifiers="Control"
            Command="{Binding CopyToClipBoardCommand}"
            CommandParameter="{Binding CurrentCell, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}" />

请注意,我从命令绑定路径中删除了 DataContext. 部分(如果未明确指定源,则 DataContext 是默认的绑定源)。

命令参数现在将是 DataGridCellInfo 类型的对象,它是 结构 ,而不是 class。

您可以修改命令参数绑定路径以提取更具体的信息。

您可以简单地使用 DataGrid 中的 CurrentCellChanged 事件 xaml。

 CurrentCellChanged="DataGrid_CurrentCellChanged"

代码...

private void DataGrid_CurrentCellChanged(object sender, EventArgs e)
        {
            var grid = sender as DataGrid;
            var cell = grid.CurrentCell.Item;
        }