0
votes

WPF DataGrid while adding new row focus is always setting to last position of cell.

How would I can set to the first cell's focus while adding new row?

1.I have simple 6 columns so when I press enter on last column it should add new row (working fine) 2.Focus should be the added row's first cell it won't happen it is always in the last cell

I am attaching my WPF Sample demo as well please correct me where I am wrong? Demo Link: WPFDemo

Thank you, Jitendra Jadav.

2
Letting the user work with a datagrid to enter data like it was excel is usually something to be avoided. Validation is a particular nightmare.Andy

2 Answers

0
votes

You could handle the CellEditEnding event and get a reference to the DataGridCell as explained in the following blog post.

How to programmatically select and focus a row or cell in a DataGrid in WPF: https://blog.magnusmontin.net/2013/11/08/how-to-programmatically-select-and-focus-a-row-or-cell-in-a-datagrid-in-wpf/

This seems to work for me:

private void dataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    DataGridRow row = dataGrid.ItemContainerGenerator.ContainerFromItem(CollectionView.NewItemPlaceholder) as DataGridRow;
    if (row != null)
    {
        dataGrid.SelectedItem = row.DataContext;
        DataGridCell cell = GetCell(dataGrid, row, 0);
        if (cell != null)
            dataGrid.CurrentCell = new DataGridCellInfo(cell);
    }
}

private static DataGridCell GetCell(DataGrid dataGrid, DataGridRow rowContainer, int column)
{
    if (rowContainer != null)
    {
        DataGridCellsPresenter presenter = FindVisualChild<DataGridCellsPresenter>(rowContainer);
        if (presenter != null)
            return presenter.ItemContainerGenerator.ContainerFromIndex(column) as DataGridCell;
    }
    return null;
}

private static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(obj, i);
        if (child != null && child is T)
            return (T)child;
        else
        {
            T childOfChild = FindVisualChild<T>(child);
            if (childOfChild != null)
                return childOfChild;
        }
    }
    return null;
}
0
votes

You could handle previewkeydown on the datagrid:

private void dg_PreviewKeyDown(object sender, KeyEventArgs e)
{
    var el = e.OriginalSource as UIElement;
    if (e.Key == Key.Enter && el != null)
    {
        e.Handled = true;
        el.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
    }
}

The markup is probably obvious but:

    <DataGrid Name="dg"
              ...
              PreviewKeyDown="dg_PreviewKeyDown"

There may well be some unexpected side effects, I just tested you hit enter in the last cell and you end up in the first cell of the next row OK.