WPF DataGrid 添加新行设置焦点第一个单元格

WPF DataGrid adding new row setting focus first cell

添加新行焦点时 WPF DataGrid 始终设置为单元格的最后一个位置。

如何在添加新行时将焦点设置到第一个单元格?

1.I 有简单的 6 列,所以当我在最后一列按回车键时,它应该添加新行(工作正常) 2.Focus 应该是添加行的第一个单元格它不会发生它总是在最后一个单元格

我也附上了我的 WPF 示例演示,请指正我哪里错了? 演示 Link:WPFDemo

谢谢, Jitendra Jadav.

您可以处理数据网格上的 previewkeydown:

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));
    }
}

标记可能很明显但是:

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

可能会有一些意想不到的副作用,我刚刚测试过你在最后一个单元格中按下回车键,然后你最终出现在下一行的第一个单元格中。

您可以处理 CellEditEnding 事件并获取对 DataGridCell 的引用,如以下博客 post.

中所述

如何以编程方式select并在 WPF 的 DataGrid 中聚焦行或单元格: https://blog.magnusmontin.net/2013/11/08/how-to-programmatically-select-and-focus-a-row-or-cell-in-a-datagrid-in-wpf/

这似乎对我有用:

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;
}

我使用了这段代码,select 第一个单元格并修复了数据网格之外的选项卡焦点:

private void table_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            var el = e.OriginalSource as UIElement;
            if (e.Key == Key.Enter && el != null)
            {
                table.CurrentCell = new DataGridCellInfo(table.Items[table.Items.Count-1], table.Columns[0]);
                table.SelectedCells.Clear();
                table.SelectedCells.Add(table.CurrentCell);
            }else if (e.Key == Key.Tab && el != null && table.SelectedCells[0].Column.DisplayIndex > table.Items.Count)
            {
                table.Focus();
            }
        }