I detected two problems with the DataGrid.
- When a row is selected in the DataGrid and I press the Down key then instead of going to the next row the DataGrid looses the focus completely.
- When giving a value to the Category which is an editable ComboBox, the edit does not work as it used to (offering a value based on the text typed so far).
After some hour of investigation it turned out the DataGridFocusBehavior class is the culprit. It successfully refocuses the DataGrid but these two mysterious error appears. I tried to modify this class hoping it might help. I tried to use Invoke instead of BeginInvoke. I tried to call the Focus() method directly not through the Dispatcher object, I tried to use some sleep before calling Focus, I also tried to change priority at BeginInvoke.
I tried to use code behind instead of Behavior but it did not help. I noticed that the Focus method is called about 20 times and I did not have any clue why. The call stack did not help. I have only seen that external code called the Behavior. It seems the SelectionChanged event is triggered a lot of times internally.
The next try was to catch the Up and the Down buttons with Commands.
private void Up(object obj) { if (PagerViewModel.SelectedRow is not DisplayTransaction selectedRow) return; var index = PagerViewModel.DisplayedRows.IndexOf(selectedRow); if (index == 0) return; var previousRow = PagerViewModel.DisplayedRows.ElementAt(index - 1); PagerViewModel.SelectedRow = previousRow; }
<DataGrid.InputBindings> <KeyBinding Key="Delete" Command="{Binding PagerViewModel.DeleteRowsCommand}" /> <KeyBinding Key="Up" Command="{Binding UpCommand}" /> <KeyBinding Key="Down" Command="{Binding DownCommand}" /> </DataGrid.InputBindings>
element.Focus(); Keyboard.Focus(element); var row = (DataGridRow)((DataGrid)element).ItemContainerGenerator.ContainerFromItem(((DataGrid)element).SelectedItem); if (row != null) { row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); // Moves focus to the next element inside the DataGrid Keyboard.Focus(row); // Set keyboard focus on the DataGrid row }