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 に答える