2011-07-27 74 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); 
    } 

關鍵是使用一個全新的最初選擇的項目從數據綁定網格的集合(即:SearchResult所),而不是使用所選項目的副本。它看起來很明顯,但花了好幾天才弄明白!感謝大家誰幫助:)

1

如果您想防止選擇更改,您可以嘗試this。如果你想恢復一個選擇,你可以使用ICollectionView.MoveCurrentTo()方法(至少你必須知道你想要選擇的項目;))。

它對我來說不是很清楚你真正想要什麼。

+0

嗨blinkmeris,對不起,遲到回覆。我試圖做的是顯示一條確認消息給用戶保存更改(在DispatchSelectionChange內),當他選擇不同的結果時,如果用戶選擇取消它,我需要將選擇恢復爲原來的選擇。 –

+0

我試過你指出的兩種方法。對我來說沒有任何工作:(鍵盤和鼠標事件敲擊不適合我的情況,而ICollectionView的行爲並不像它應該的那樣,即使CurrentItem被同步,網格也可視化地顯示另一個元素爲選中。似乎我在WPF中的錯誤... –