2

我有具有 SelectionUnit = FullRow 的数据网格。当我在单元格上单击时,如果我按 Escape 键,它将进入编辑模式并且没有更新。它从编辑模式出来,但仍然有焦点(虚线)

但是如果我更新数据然后按 Escape 键,它基本上使用(CellEditEnding 事件)提交数据,然后当我尝试从代码中将焦点设置到该单元格时,它不起作用,整个数据网格失去焦点。

请参阅下面的代码。

//更新数据后按Escape时提交编辑代码

 void DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {
        if (!_isManualEditCommit)
        {
            _isManualEditCommit = true;
            DataGrid grid = (DataGrid)sender;
            grid.CommitEdit(DataGridEditingUnit.Row, true);
            isManualEditCommit = false;
        }        
    } 


 void RhinoDataGrid_Loaded(object sender, RoutedEventArgs e)
  {

 RoutedEventHandler CellFocusedChangedHandler = new  RoutedEventHandler(FocusChangedHandler);
AddHandler(DataGridCell.GotKeyboardFocusEvent, CellFocusedChangedHandler);
}

  // Setting focus back to cell after updating data using Escape key

   private void FocusChangedHandler(object sender, RoutedEventArgs args)
    {
        if (args.RoutedEvent.RoutingStrategy == RoutingStrategy.Bubble)
        {
            FrameworkElement DataGridCellObj = args.OriginalSource as FrameworkElement;
           if (Keyboard.IsKeyDown(Key.Escape))
            {
                if (DataGridCellObj != null)
                {
                    DataGridCell dgCell = DataGridCellObj as DataGridCell;
                    if (dgCell != null && !dgCell.IsEditing && !dgCell.IsReadOnly)
                    {
                        if (!dgCell.IsFocused)
                        {
                            dgCell.Focus();
                        }
                        DataGridRow dr = VisualTreeHelpers.FindVisualParent<DataGridRow>(dgCell);
                        int rIndex = ((DataView)this.ItemsSource).Table.Rows.IndexOf(((DataRowView)(dr.Item)).Row);
                        DataGridCellInfo dgCellInfo = new DataGridCellInfo(this.Items[rIndex], dgCell.Column);
                        if (dgCellInfo != null)
                        {
                            FocusManager.SetIsFocusScope(dgCell, true);
                            FocusManager.SetFocusedElement(dgCell, dgCell);
                            dgCell.BorderThickness = new Thickness(7);
                        }
                    }
                }
            }
        }

在此处输入图像描述

请帮助谢谢

4

0 回答 0