C# – Move Focus to Next Cell on Enter Key Press in WPF DataGrid

cmvvmwpfwpfdatagrid

I want to have a Custom DataGrid which can,

  1. Move to next cell when Enter key is pressed also if it is in edit mode.
  2. When the last column in the current row is reach, the focus should move to the first cell of next row.
  3. On reaching to next cell, if the cell is editable, it should automatically became editable.
  4. If the cell contains an ComboBox not comboboxcolumn, the combobox should DropDownOpen.

Please help me in this. I have been trying from the past few day by creating a Custom DataGrid and wrote some code in

protected override void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e)

But I failed.

Best Answer

A much simpler implementation. The idea is to capture the keydown event and if the key is "Enter", then move to the next tab which is next cell of the grid.

/// <summary>
/// On Enter Key, it tabs to into next cell.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DataGrid_OnPreviewKeyDown(object sender, KeyEventArgs e)
{
    var uiElement = e.OriginalSource as UIElement;
    if (e.Key == Key.Enter && uiElement != null)
    {
        e.Handled = true;
        uiElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
    }
}
Related Topic