wpf 键盘焦点到 DataGrid

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20537073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:11:40  来源:igfitidea点击:

Keyboard focus to DataGrid

c#wpfdatagridkeyboardfocus

提问by simmeone

I have a WPF DataGrid and want to set the focus to the first item so that the user can navigate with the keyboard in the list of items, when the dialogue is opened the first time. With datagrid.Focus ( ); I can set the focus to the DataGrid, but this is apparently not the keyboard focus, because when I press the arrow down key, I cannot navigate in the DataGrid. The focus jump to the textbox "Description" but that is not what I want (see picture).

我有一个 WPF DataGrid 并希望将焦点设置为第一个项目,以便用户可以在第一次打开对话框时使用项目列表中的键盘进行导航。用datagrid.Focus(); 我可以将焦点设置到 DataGrid,但这显然不是键盘焦点,因为当我按下箭头键时,我无法在 DataGrid 中导航。焦点跳转到文本框“描述”,但这不是我想要的(见图)。

enter image description here

在此处输入图片说明

How can I set the focus and the keyboard focus in a correct way to the DataGrid? Thank for your help.

如何以正确的方式将焦点和键盘焦点设置到 DataGrid?感谢您的帮助。

采纳答案by simmeone

Ok, I found a solution. This works for me

好的,我找到了解决方案。这对我有用

Keyboard.Focus (GetDataGridCell (dataGridFiles.SelectedCells[0]));

private System.Windows.Controls.DataGridCell GetDataGridCell (System.Windows.Controls.DataGridCellInfo cellInfo)
{
  var cellContent = cellInfo.Column.GetCellContent (cellInfo.Item);

  if (cellContent != null)
    return ((System.Windows.Controls.DataGridCell) cellContent.Parent);

  return (null);
}

Now, I got the right focus and can navigate with keyboard.

现在,我获得了正确的焦点并且可以使用键盘进行导航。

回答by Rohit Vats

Try giving keyboard focus manually using Keyboard.Focus-

尝试使用Keyboard.Focus手动设置键盘焦点-

Keyboard.Focus(dataGrid);

回答by StanleyIPC

A clear way to do this:

一个明确的方法来做到这一点:

DataGridCell dgc = DataGridView.FindChildren<DataGridCell>(true).First();
Keyboard.Focus(dgc);

Explanation: The method FindChildren will get a IEnumarable, in this case above the T is DataGridCell. The option "true" is used to force the search in Visual Tree view and the ".First()" is from LINQ to get the first result of IEnumerable. So, you'll have the first DataGridCell of datagrid, now u can set the focus.

说明:FindChildren 方法会得到一个IEnumarable,在这个例子上面的T 是DataGridCell。选项“true”用于强制在 Visual Tree 视图中搜索,“.First()”来自 LINQ 以获取 IEnumerable 的第一个结果。因此,您将拥有 datagrid 的第一个 DataGridCell,现在您可以设置焦点。

I lost much time to find this way, I hope it's helpful.

我失去了很多时间来找到这种方式,我希望它会有所帮助。

English isn't my first language, so please excuse any mistakes.

英语不是我的第一语言,所以请原谅任何错误。