I have a DataGrid in WPF. I use this technique to bind SelectedItems to my VM. I created a command which swap the two selected rows of the DataGrid. (Actually I swap the Ids, update the db, and reload (ordered by id) the ObservableCollection of the DataGrid) After that I see no selection in the DataGrid but dataGrid.SelectedItems still contains the two rows. I checked this in CodeBehind. If I select a row then dataGrid.SelectedItems contains 3 elements now. I tried to clear the selection from CodeBehind without success. I tried this methods.
dataGrid.UnselectAll();
dataGrid.UnselectAllCells();
dataGrid.SelectedCells.Clear();
dataGrid.SelectedItem = null;
dataGrid.IsEnabled = false;
dataGrid.IsEnabled = true;
Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => dataGrid.Items.Refresh()));
If I select two rows and try to unselect before swapping the rows then UnselectAll() works perfectly.
Ok, the solution was not how to unselect the rows but when to do it. It worked perfectly before swapping the rows. I could do it from ViewModel.
Pager.SelectedRow = null;
where SelectedRow is bound to DataGrid.SelectedItem.