WPF数据网格取消选择更改



我正在以MVVM方式使用WPF DataGrid,并且在从ViewModel恢复选择更改时遇到麻烦。

有什么行之有效的方法可以做到这一点吗?我最近试用过的代码如下。现在我甚至不介意在背后的代码中投资一个hack。

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

这里的关键是从数据绑定网格的集合(即:SearchResults)中使用一个全新的原始选择项,而不是使用所选项的副本。这看起来很明显,但我花了好几天才弄明白!谢谢大家的帮助:)

如果你想阻止选择改变,你可以试试这个

如果你想恢复一个选择,你可以使用ICollectionView.MoveCurrentTo()方法(至少你必须知道你想选择什么项目;))。

我不太清楚你到底想要什么

最新更新