0

I have a DataGrid implemented in an MVVM/Prism application. The DataGrid supports Cut/Copy/Paste/Delete through a context menu and keyboard gestures.

I find that when a row is deleted/cut the entire DataGrid loses focus and keyboard focus moves to the last focused control.

Is there anyway to prevent this?

After removing a row I may want to re-paste into the DataGrid. Furthermore if the grid is empty there is no way at all for it to get keyboard focus. Clicking an empty grid does not give it focus.

Here is a similar question, but it doesn't solve the issue for me: DataGrid Looses Focus When Delete Key is Pressed

Community
  • 1
  • 1
Terrence
  • 747
  • 1
  • 10
  • 27

2 Answers2

1

You could set the DataGrids Focus in the PreviewKeyDown-Event

private void TheDataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Delete)
    {
       var grid = (DataGrid)sender;
       FocusManager.SetFocusedElement(Window.GetWindow(grid), grid); //not tested
    }
}

If you dont want to put code in code-behind use AttachedProperties in combination with the DependencyPropertyChanged-Event.
How to set set focus.

Florian Gl
  • 5,984
  • 2
  • 17
  • 30
  • Yes... this works well, Thanks. I find that I must handle Delete and Ctrl-X. Also, I'm forcing focus on MouseDown (for focusing an empty grid) and ContextMenuClosing (for focusing after clicking Cut/Delete). – Terrence Apr 05 '13 at 22:23
  • 3
    I spoke a bit too soon. PreviewKeyDown has the unfortunate side-effect of being called when editing a cell. In those cases it steals Focus from the cell. I found that setting focus in UnloadingRow instead works well. – Terrence Apr 06 '13 at 00:19
0

A dirty solution might be to handle the LostFocus event exposed by DataGrid and set focus on the control.

It arguably marginally infringes on the MVVM pattern i.e keeping the view dumb as hell, but it's still view code.

Drew R
  • 2,988
  • 3
  • 19
  • 27
  • How would you propose distinguishing between user clicked outside of DataGrid type-of-lost-focus and the one when something was deleted? – wondra Jan 15 '20 at 14:58