使用箭头键的 WPF 数据网格单元格循环

WPF data grid cell loop using arrow keys

我有一个简单的数据网格,我使用向下箭头键浏览里面的项目,但是当我到达最后一行并继续按下时,它停止了并且无法再导航,就像它已经失去了焦点。我如何使用键循环遍历它?在标记中是否有 属性 或我需要在后面的代码中这样做?

据我所知,没有办法从标记中更改默认的 selection 行为,因此您需要在后面的代码中执行此操作。

此处描述的默认行为:

Default Keyboard and Mouse Behavior in the DataGrid Control

这应该是一件简单的事情,您可以在 DataGrid 的 PreviewKeyDown 事件处理程序中执行类似的操作:

if (e.Key == Key.Down && MyDataGrid.SelectedIndex == (MyDataGrid.Items.Count - 1))
{
    MyDataGrid.SelectedIndex = 0;                
    MyDataGrid.ScrollIntoView(MyDataGrid.SelectedItem);
    e.Handled = true;
}

但是,尽管这会 select 顶行,selected 单元格的键盘焦点会干扰以后的按键操作。

如果您真的想要这种行为,这里有一篇非常好的文章:

WPF: Programmatically Selecting and Focusing a Row or Cell in a DataGrid