即使在wpf datagrid中失去焦点,单元格仍保持编辑模式

Vis*_*hal 8 c# wpf xaml datagrid mvvm

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

我已经使用了EnterKeyTravarsal类,这样我可以使用EnterTAB.

另外,根据一些条件,我使用InputBindings在ViewModel中向DataGrid添加一个新行.

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

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

Asi*_*itK 3

更新你的班级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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)