我正在以MVVM方式使用WPF DataGrid,并且无法从ViewModel恢复选择更改。
有没有经过验证的方法可以做到这一点?我最新的试用代码如下。现在我甚至不介意在后面的代码中投入黑客。
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);
}
}
}
答案 0 :(得分:3)
经过几天的反复试验,终于搞定了。以下是代码:
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);
}
这里的关键是使用数据绑定网格集合中最新选择的全新项目(即:SearchResults),而不是使用所选项目的副本。它看起来很明显,但我花了好几天才弄清楚!感谢所有帮助过的人:)
答案 1 :(得分:1)
如果您想阻止选择更改,可以尝试this。
如果你想恢复选择,你可以使用ICollectionView.MoveCurrentTo()方法(至少你必须知道你想要选择的项目;))。
我不太清楚你真正想要的是什么。