Refresh WPF DataGrid without losing cell focus
The best way is not to use dataGrid.Items.Refresh() as update mechanism. It sounds like the underlying objects are already updated separately. If they implement INotifyPropertyChanged, you should try to set the binding mode for the colum as TwoWay Binding:
<DataGridTextColumn Binding="{Binding xyz, Mode=TwoWay}"/>
i think you may get the present focus and after grid is refreshed give the selected cell back its focus something like
int index = 11;myDataGrid.SelectedItem = myDataGrid.Items[index];myDataGrid.ScrollIntoView(myDataGrid.Items[index]);DataGridRow dgrow = (DataGridRow)myDataGrid.ItemContainerGenerator.ContainerFromItem(myDataGrid.Items[index]);dgrow.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
also check this out it may help you
Your cells lose focus because you change the underlying collection (ItemsSource). There is no beautiful way, as far as I recall, to get the cell. For the row :
If you work with MVVM, you can memorize your SelectedItem
or SelectedIndex
and restore it after the reload is done by binding. That will get you in the right row, for a start. Both have different drawbacks:
SelectedItem
requires a bit more work. Make sure you overrideEquals
andGetHashCode
in the underlying objects if you use it. If your item was number 5 in the collection and during the reload another row appears before it, you will still end up in the right lineSelectedIndex
is the quickest solution, but is only a numeric position. If you select entry number 5 and the reload merges in rows before it, you will end up with the wrong selected row.
As I said, I haven't tried with the cells, but you can read this for a start. Maybe you can apply it to your issue.