I am working with WPF DataGrid in the MVVM manner and having trouble reverting the selection change from the ViewModel.
Is there any proven way to do this? My latest tried out code is below. Now I do not even mind investing on a hack inside the code behind.
public SearchResult SelectedSearchResult
{
get { return _selectedSearchResult; }
set
{
if (value != _selectedSearchResult)
{
var originalValue = _selectedSearchResult != null ? _selectedSearchResult.Copy() : null;
_selectedSearchResult = value;
if (!DispatchSelectionChange(value)) // Returns false if the selection has to be cancelled.
{
_selectedSearchResult = originalValue;
// Invokes the property change asynchronously to revert the selection.
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new Action(() => NotifyOfPropertyChange(() => SelectedSearchResult)));
return;
}
NotifyOfPropertyChange(() => SelectedSearchResult);
}
}
}
After days of trial and error, finally got it working. Following is the code:
public ActorSearchResultDto SelectedSearchResult
{
get { return _selectedSearchResult; }
set
{
if (value != _selectedSearchResult)
{
var originalSelectionId = _selectedSearchResult != null ? _selectedSearchResult.Id : 0;
_selectedSearchResult = value;
if (!DispatchSelectionChange(value)) // Returns false if the selection has to be cancelled.
{
// Invokes the property change asynchronously to revert the selection.
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new Action(() => RevertSelection(originalSelectionId)));
return;
}
NotifyOfPropertyChange(() => SelectedSearchResult);
}
}
}
private void RevertSelection(int originalSelectionId)
{
_selectedSearchResult = SearchResults.FirstOrDefault(s => s.Id == originalSelectionId);
NotifyOfPropertyChange(() => SelectedSearchResult);
}
Key here is to use a brand new originally selected item from the databound grid's collection (ie: SearchResults) rather than using a copy of the selected item. It looks obvious, but took days for me to figure it out! Thanks for everyone who helped :)