3

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

2 回答 2

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)的全新的最初选定项,而不是使用选定项的副本。看起来很明显,但我花了几天时间才弄清楚!感谢所有帮助过的人:)

于 2011-08-26T06:46:09.560 回答
1

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

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

我不太清楚你真正想要什么。

于 2011-07-27T12:40:16.173 回答