【问题标题】:WPF DataGrid adding new row setting focus first cellWPF DataGrid 添加新行设置焦点第一个单元格
【发布时间】:2018-10-04 11:04:42
【问题描述】:

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

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

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

我也附上了我的 WPF 示例演示,请纠正我哪里错了? 演示链接:WPFDemo

谢谢, Jitendra Jadav。

【问题讨论】:

  • 让用户使用数据网格来输入数据,就像它是 excel 一样,通常是要避免的。验证是一场特别的噩梦。

标签: wpf datagrid focus


【解决方案1】:

您可以处理CellEditEnding 事件并获取对DataGridCell 的引用,如以下博客文章中所述。

如何在 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;
}

【讨论】:

  • 感谢您的建议,但只有一个问题,在按第一个单元格的输入时它正在添加新行我想在按最后一个单元格的输入时添加新行。可以请纠正它或给我一些指导,这可能会有很大的帮助
  • 这是一个完全不同的问题。您最初的问题是“如何在添加新行时设置第一个单元格的焦点?”我相信这个问题已经得到解答。如果您有其他问题,请提出一个新问题。如果可以的话,我很乐意帮助你。但请不要在 cmets 字段中提出其他问题。
  • 嗨@mm8,这是正确的,但如果你看到我提到了我的要求,如果你想要另一个问题,请检查它,然后我会发布新问题,请让我知道。谢谢
  • 如前所述,您最初的问题是如何在添加新行时聚焦第一个单元格。如果您还有其他问题,请再次提出新问题。
【解决方案2】:

您可以在数据网格上处理 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"

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

【讨论】:

  • 谢谢@Andy,但不幸的是你的建议不起作用
  • 如果数据网格中有任何数据,我的建议肯定有效。恐怕我真的不想在这里下载并深入研究您的应用程序。
猜你喜欢
  • 2018-03-23
  • 1970-01-01
  • 1970-01-01
  • 2011-11-25
  • 1970-01-01
  • 2011-10-12
  • 1970-01-01
  • 2011-01-10
  • 2022-01-16
相关资源
最近更新 更多