Question

I have datagrid which has SelectionUnit = FullRow. When I clcik on cell, it goes to edit mode and without updation if I press Escape key. it came out from edit mode but still it has focus (dotted line)

But If I update data and then press Escape key, it basically commit data using (CellEditEnding event) and then when I try to set focus to that cell from code, it didnot work, whole datagrid looses focus.

see my code below.

//CommitEdit code when I press Escape after updating data

 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);
                        }
                    }
                }
            }
        }

enter image description here

pls help Thanks

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top