2011-07-27 35 views
2

私はMVVMの方法でWPF DataGridを使用しており、ViewModelからの選択変更を元に戻すことに問題があります。WPF DataGridキャンセル選択の変更

これを行う実績のある方法はありますか?最近試したコードは以下の通りです。今では、コードの中にハックを入れて投資することさえ気にしません。

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

答えて

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)からのブランドの新しい最初に選択した項目を使用することです。それは明らかですが、私はそれを理解するために何日もかかりました!お手数をおかけしていただきありがとうございます。

1

選択変更を防止したい場合は、thisを試すことができます。

選択を元に戻したい場合は、ICollectionView.MoveCurrentTo()メソッドを使用できます(少なくとも選択するアイテムを知っておく必要があります)))。

あなたが本当に欲しいものは私にはあまり明確ではありません。

+0

こんにちはblinkmeris、遅く返事を申し訳ありません。私が何をしようとしているのは、彼が別の結果を選択したときに(DispatchSelectionChange内の)変更を保存するための確認メッセージをユーザーに表示し、ユーザーがキャンセルすることを選択した場合、元のものに戻す必要があります。 –

+0

あなたが指摘した両方の方法を試しました。私の場合キーボードとマウスのイベントのタップは適切ではありません。そして、ICollectionViewは動作しません。その場合、CurrentItemが同期されていても、グリッドは視覚的に別の要素を表示しますWPFのバグです。 –

関連する問題