Keyboard focus to DataGrid

后端 未结 3 480
陌清茗
陌清茗 2021-01-18 01:10

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

相关标签:
3条回答
  • 2021-01-18 01:16

    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.

    0 讨论(0)
  • 2021-01-18 01:30

    Try giving keyboard focus manually using Keyboard.Focus -

    Keyboard.Focus(dataGrid);
    
    0 讨论(0)
  • 2021-01-18 01:37

    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.

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

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

    0 讨论(0)
提交回复
热议问题