wpf datagrid添加新的行设置焦点第一单元格



wpf datagrid添加新的行焦点始终设置为单元格的最后位置。

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

1.我有简单的6列,所以当我按下最后一列Enter时,它应该添加新行(工作正常(2.对焦应该是添加的第一个单元格,它不会发生,它始终在最后一个单元格中

我还附加了我的WPF样品演示,请在我错的地方纠正我吗?演示链接:wpfdemo

谢谢,Jitendra Jadav。

您可以在datagrid上处理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的引用,如以下博客文章中所述。

如何在wpf中的datagrid中进行编程选择并聚焦一个或牢房且焦点-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;
}

我使用此代码,选择第一个单元格,然后fix tab focuse out datagride:

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

相关内容

最新更新