15

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.

7 Answers 7

15

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));
    }
}
1
  • 1
    The issues i am facing with your code is i have multipleDataGridTemplateColumn each having a textbox inside...The code moves focus to the next cell/textbox , but not entirely, i mean the textbox get outer black spots/lines.I have to press enter twice in order to entirely focus to the next cell/textbox...Any fix? Jun 21, 2018 at 7:06
6
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;
}
3
  • I have done something similar in a few projects, the code is very very similar. I just extended the datagrid and encapsulated a bulk of what you are doing in it. So I can vouch that this/your answer definitely works great! +1 May 10, 2012 at 20:22
  • 19
    It would be nice to see th missing code: GetRow(), GetVisualChild<T>() and what is dgIssuance?
    – bitbonk
    Oct 9, 2012 at 13:29
  • 1
    Why are you passing a hardcoded values to your GetCell function??? The question was about moving to next cell when Enter key is pressed, but you're trying to get a last cell in your 2-nd column on Enter click. Why?
    – AndreyS
    Apr 14, 2015 at 9:12
6

How about this solution? Cancel the action of the Enter key by setting Handled=true and press the Tab key.

public Constructor()
{
  InitializeComponent(); 
  this.SampleDataGrid.PreviewKeyDown += MoveCellOnEnterKey;
}

private void MoveCellOnEnterKey(object sender, KeyEventArgs e)
{
  if(e.Key == Key.Enter)
  {
    // Cancel [Enter] key event.
    e.Handled = true;
    // Press [Tab] key programatically.
    var tabKeyEvent = new KeyEventArgs(
      e.KeyboardDevice, e.InputSource, e.Timestamp, Key.Tab);
    tabKeyEvent.RoutedEvent = Keyboard.KeyDownEvent;
    InputManager.Current.ProcessInput(tabKeyEvent);
  }
}
2
public class DataGrid : System.Windows.Controls.DataGrid
{
    private void PressKey(Key key)
    {
        KeyEventArgs args = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, key);
        args.RoutedEvent = Keyboard.KeyDownEvent;
        InputManager.Current.ProcessInput(args);
    }
    protected override void OnCurrentCellChanged(EventArgs e)
    {
        if (this.CurrentCell.Column != null)                
            if (this.CurrentCell.Column.DisplayIndex == 2)
            {

                if (this.CurrentCell.Item.ToString() == "--End Of List--")
                {
                    this.MoveFocus(new TraversalRequest(FocusNavigationDirection.Down));
                }
            }
            else if (this.CurrentCell.Column != null && this.CurrentCell.Column.DisplayIndex == this.Columns.Count() - 1)
            {
                PressKey(Key.Return);
                DataGridCell cell = DataGridHelper.GetCell(this.CurrentCell);
                int index = DataGridHelper.GetRowIndex(cell);
                DataGridRow dgrow = (DataGridRow)this.ItemContainerGenerator.ContainerFromItem(this.Items[index]);
                dgrow.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
            }
    }
    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            DataGridRow rowContainer = (DataGridRow)this.ItemContainerGenerator.ContainerFromItem(this.CurrentItem);
            if (rowContainer != null)
            {
                int columnIndex = this.Columns.IndexOf(this.CurrentColumn);
                DataGridCellsPresenter presenter = UIHelper.GetVisualChild<DataGridCellsPresenter>(rowContainer);
                if (columnIndex == 0)
                {
                    DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
                    TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);
                    request.Wrapped = true;
                    cell.MoveFocus(request);
                    BeginEdit();
                    PressKey(Key.Down);
                }
                else
                {
                    CommitEdit();
                    DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
                    TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);
                    request.Wrapped = true;
                    cell.MoveFocus(request);
                }
                this.SelectedItem = this.CurrentItem;
                e.Handled = true;
                this.UpdateLayout();
            }
        }
    }
}

For the time being, I have written this and its working for me.

1
  • I get the error 'Error 137 The type 'my:DataGridComboBoxColumn' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.' when I extend datagrid class wats wrong
    – Mussammil
    Dec 13, 2013 at 5:46
0
    Public Sub SendKey(ByVal key As Key)
     Dim args As New KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, key)
        args.RoutedEvent = Keyboard.KeyDownEvent
        InputManager.Current.ProcessInput(args)
    End Sub
Private Sub dataGrid_PreviewKeyDown(sender As Object, e As KeyEventArgs) Handles dataGrid.PreviewKeyDown
        Dim i As UIElement = e.OriginalSource
        Dim DG As DataGrid = sender
        If (e.Key = Key.Enter Or e.Key = Key.Return) AndAlso i IsNot Nothing Then
            MyBase.OnKeyDown(e)
            DG.CommitEdit()
            SendKey(Key.Tab)
            e.Handled = True
        End If
    End Sub
0

The key method is 'dataGrid.SetKeyboardFocusToCell'. So we can attach the KeyDown event:

    private void dataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        DataGridTemplateColumn col = (DataGridTemplateColumn)dataGrid.CurrentColumn;
        if (col != null)
        {
            switch (col.SortMemberPath)
            {
                case "From":
                    if (e.Key == Key.Enter && Keyboard.Modifiers == ModifierKeys.None) // Pure Enter
                    {
                        e.Handled = true;
                        int columnIndex = dataGrid.GetColumnIndex(colTo);
                        DataGridRow currentRow = dataGrid.GetRow(dataGrid.CurrentItem);

                        dataGrid.SetKeyboardFocusToCell(dataGrid.CurrentItem, columnIndex);
                        Dispatcher.Invoke(() =>
                        {
                            GridTimeSpanBox timeSpanBox = VisualTree.FindChild<GridTimeSpanBox>(currentRow, tsb => tsb.Name == "tsbTo", true);
                            timeSpanBox.SelectAll();
                        }, System.Windows.Threading.DispatcherPriority.ContextIdle);
                    }
                    break;
            }
        } // col != null
    }

    /// <summary>
    /// Get the row container that holds the 'item'
    /// </summary>
    public DataGridRow GetRow(object item)
    {
        return (DataGridRow)ItemContainerGenerator.ContainerFromItem(item);
    }

    /// <summary>
    /// Gets the index of a 'DataGridColum' or 'DataGridTemplateColumn' in the 'Columns' list. This doesn't change if the user
    /// reorders the columns.
    /// </summary>
    public int GetColumnIndex(DataGridColumn column)
    {
        return this.Columns.IndexOf(column);
    }

In this example the text in the following box is selected too. Can be useful for fields where most of the time the content is replaced by typing a new one.

Important to note that generally operations after 'dataGrid.SetKeyboardFocusToCell()' must be sent over the dispatcher to allow the UI to finish updating. Otherwise strange things can happen.

With this scheme you could for example even insert a row behind the current one.

0
private void dg_ExpenseItem_PreviewKeyDown(object sender, KeyEventArgs e)           
    {
        try
        {
            DataGrid grid = (DataGrid)sender;
            if (e.Key == Key.Enter)
            {
                e.Handled = true;
                var cell = GetCell(grid, grid.SelectedIndex, grid.CurrentCell.Column.DisplayIndex+1);
                if (cell != null)
                {
                    cell.IsSelected = true;
                    cell.Focus();
                    grid.BeginEdit();
                }
            }
        }
        catch (Exception ex)
        {
            
        }
    }
public static DataGridCell GetCell(DataGrid grid, int row, int column)
    {
        var rowContainer =  GetRow(grid, 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
                    grid.ScrollIntoView(rowContainer, grid.Columns[column]);
                    cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                }
                return cell;
            }
        }
        return null;
    }
static public DataGridRow GetRow(DataGrid dg, int index)
    {
        DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
        if (row == null)
        {
            // may be virtualized, bring into view and try again
            dg.ScrollIntoView(dg.Items[index]);
            row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
        }
        return row;
    }
    static T GetVisualChild<T>(Visual parent) where T : Visual
    {
        T child = default(T);
        int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < numVisuals; i++)
        {
            Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
            child = v as T;
            if (child == null)
            {
                child = GetVisualChild<T>(v);
            }
            if (child != null)
            {
                break;
            }
        }
        return child;
    }
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Nov 5, 2022 at 16:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.