gpt4 book ai didi

WPF DataGrid 取消选择更改

转载 作者:行者123 更新时间:2023-12-01 23:34:53 26 4
gpt4 key购买 nike

我正在以 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);
}
}
}

最佳答案

经过几天的反复试验,终于成功了。以下是代码:

    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);
}

此处的关键是使用来自数据绑定(bind)网格集合(即:SearchResults)的全新最初选择的项目,而不是使用所选项目的副本。看起来很明显,但我花了几天时间才弄明白!感谢所有帮助过的人:)

关于WPF DataGrid 取消选择更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6843727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com