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

时间:2014-04-30 16:14:34

标签: c# wpf xaml mvvm datagrid

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

我使用了EnterKeyTravarsal类,因此我可以使用 Enter 作为 TAB

同样根据一些条件,我使用InputBindings在ViewModel中向DataGrid添加一个新行。

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

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

2 个答案:

答案 0 :(得分:2)

更新您的班级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();
        }
    }
}

答案 1 :(得分:1)

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

我记得我有一个类似的问题,我用它来解决它 任

this.grid.CommitEdit();

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

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

我在插入新行之前调用这些方法,但是我记得我有很多问题要让它们正常工作,最后却没有正确理解它们(虽然它们工作得很好),对不起:S

编辑:代码公共DataGrid

public DataGrid MyGrid
{
  get 
  {
    return this.grid;
  }
}
相关问题