WPF DataGrid 取消选择更改
我正在以 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);
}
}
}
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);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
经过几天的反复尝试,终于成功了。以下是代码:
这里的关键是使用数据绑定网格集合中的全新的原始选定项目(即:SearchResults),而不是使用选定项目的副本。这看起来很明显,但我花了几天时间才弄清楚!感谢所有提供帮助的人:)
After days of trial and error, finally got it working. Following is the code:
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 :)
如果您想阻止选择更改,可以尝试这个。
如果你想恢复选择,你可以使用 ICollectionView.MoveCurrentTo() 方法(至少你必须知道你想要选择哪个项目;))。
我不太清楚你真正想要什么。
if you want to prevent the selection change you can try this.
if you want to revert a selection, you can just use ICollectionView.MoveCurrentTo() methods (at least you must have to know what item you want to select ;)).
its not quite clear to me what you really want.