【问题标题】:cell remains in edit mode even after it loses focus in wpf datagrid即使在 wpf 数据网格中失去焦点后,单元格仍处于编辑模式
【发布时间】:2014-06-17 01:43:27
【问题描述】:

我有一个 DataGrid,其中有两列,即 NameGroup

我使用了EnterKeyTravarsal Class,所以我可以使用Enter作为TAB

还基于某些条件,我使用 InputBindings 在 ViewModel 中的 DataGrid 中添加了一个新行。

但是当添加新行时,我可以看到在添加新行之前聚焦的最后一个单元格仍处于编辑模式。

Here 是我创建的一个示例项目,用于清楚地解释我的问题。

【问题讨论】:

    标签: c# wpf xaml mvvm datagrid


    【解决方案1】:

    更新你的班级EnterKeyTraversal

    static void ue_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
    {
        var ue = e.OriginalSource as FrameworkElement;
        DataGrid dg = FindVisualParent<DataGrid>(ue) as DataGrid;
        DataGridCell cell = FindVisualParent<DataGridCell>(ue);
    
        if (e.Key == Key.Enter)
        {
            //e.Handled = true;
    
            if (dg != null)
            {
                dg.CommitEdit();
            }
    
            if (cell != null)
            {
                cell.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }
            else
            {
                ue.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }
    
            if (dg != null)
            {
                dg.BeginEdit();
            }
        }
    }
    

    【讨论】:

    • 在这种情况下,您还需要处理 tab 键
    • 您的解决方案按预期工作。但是现在我得到了另一个与上述解决方案完全相同的问题的示例项目。当我在任何行的最后一个单元格上按 enter 时,会添加一个新行,并且上一行的最后一个单元格保持在编辑模式。你能检查这个样本吗:drive.google.com/file/d/0B5WyqSALui0bUUJlUU85T2RzZXc/… 我试图在第 1 行之前应用你的 dg.CommitEdit() 解决方案。 314 在 mainwindow.xaml
    • 另外,我注意到如果我使用 DataGridTemplateColumn 而不是 DataGridTextColumn,那么我不会遇到上述问题,我的意思是它可以正常工作。
    【解决方案2】:

    我没有时间下载您的所有代码,但我会尽力提供帮助。

    我记得我有一个类似的问题,我用 要么

    this.grid.CommitEdit();
    

    this.grid.CommitEdit(DataGridEditingUnit.Row, true);
    

    在您的情况下,您可能需要使用“DataGridEditingUnit.Cell”

    我在插入新行之前调用了这些方法,但我记得我遇到了很多问题才能让它们工作,最后没能正确理解它们(虽然它们工作正常),抱歉 :S

    编辑:公共数据网格的代码

    public DataGrid MyGrid
    {
      get 
      {
        return this.grid;
      }
    }
    

    【讨论】:

    • 感谢 Javi 试图通过回答这个问题来帮助我。但是我怎样才能使用this.grid?我正在使用 MVVM。那么,如何在 ViewModel 中引用 DataGrid?
    • 抱歉,我的 DataGrid 在代码隐藏中。在 MainWindow.xaml 中,只需输入 x:Name="grid",然后尝试在 xaml.cs 中使用 this.grid。如果您在 MainWIndow.xaml.cs 中没有逻辑,只需在其中创建一个返回 xaml 的 DataGrid 的公共属性
    • just make there a public property that returns the DataGrid of the xaml. 你能解释一下如何将该新属性绑定到 dataGrid 吗?
    • 我已经试过你的代码了。但是我在这一行遇到编译错误:return this.grid 说它找不到元素grid。这很明显,因为我的 ViewModel 不会在 View 中找到元素,因为它不知道 View 的控件。
    • 我正在查看您的 MainWindow.xaml.cs 我看到您有“private void DataGrid_CellGotFocus”。你有没有尝试捕捉细胞的 LostFocus ?被解雇了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    相关资源
    最近更新 更多