2011-07-27 4 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

시행 착오 끝에 결국 마침내 작동하게되었습니다. 오히려 선택한 항목의 복사본을 사용하는 것보다 (의 SearchResult 즉) 여기

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

키는 데이터 바인딩 된 그리드의 컬렉션 브랜드의 새로운 원래 선택한 항목을 사용하는 것입니다 : 다음은 코드입니다. 그것은 명백하게 보인다. 그러나 나를 위해 그것을 이해하는 날을졌다! 도와 주신 모든 분들께 감사드립니다.

1

선택 변경을 막으려는 경우 시도해 볼 수 있습니다 this.

선택을 되돌리려면 ICollectionView.MoveCurrentTo() 메서드를 사용할 수 있습니다. 적어도 선택할 항목을 알고 있어야합니다.)).

내게 당신이 정말로 원하는 것이 분명하지 않습니다.

+0

안녕하세요, blinkmeris, 늦게 답장을 드려 죄송합니다. 내가 무엇을하려고하는지 그가 다른 결과를 선택할 때 (DispatchSelectionChange 내부) 변경 내용을 저장하려면 사용자에게 확인 메시지를 표시하고 사용자가 취소하도록 선택한 경우, 나는 원래 한 선택을 되돌릴 필요가있다. –

+0

당신이 지적한 두 가지 방법을 시도했습니다. 아무 것도 작동하지 않는 것 같습니다 : 키보드와 마우스 이벤트 탭핑이 제 경우에는 적합하지 않습니다. 그리고 ICollectionView는 정상적으로 작동하지 않습니다.이 경우는 CurrentItem이 동기화되어 있어도 격자가 시각적으로 다른 요소를 보여줍니다 WPF에 버그가있는 것 같아요. –