Search code examples
c#wpfmvvmwpfdatagrid

Move Focus to Next Cell on Enter Key Press in WPF DataGrid?


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.


Solution

  • private void dg_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        try
        {
            if (e.Key == Key.Enter)
            {
                e.Handled = true;
                var cell = GetCell(dgIssuance, dgIssuance.Items.Count - 1, 2);
                if (cell != null)
                {
                    cell.IsSelected = true;
                    cell.Focus();
                    dg.BeginEdit();
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox(ex.Message, "Error", MessageType.Error);
        }
    }  
    
    public static DataGridCell GetCell(DataGrid dg, int row, int column)
    {
        var rowContainer = GetRow(dg, row);
    
        if (rowContainer != null)
        {
            var presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
            if (presenter != null)
            {
                // try to get the cell but it may possibly be virtualized
                var cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                if (cell == null)
                {
                    // now try to bring into view and retreive the cell
                    dg.ScrollIntoView(rowContainer, dg.Columns[column]);
                    cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                }
                return cell;
            }
        }
        return null;
    }