2011-08-23 9 views
1

WPF ComboBox가 있고 MVVM을 사용하여 ItemsSource 및 SelectedItem 속성을 바인딩합니다. 기본적으로 사용자가 콤보 상자의 특정 항목을 선택하면 콤보 상자가 다른 항목을 선택합니다.WPF ComboBox SelectedItem binding

<ComboBox ItemsSource="{Binding TestComboItemsSource}" SelectedItem="{Binding TestComboItemsSourceSelected}"></ComboBox> 

데모 용으로 SelectedItem을 업데이트하는 버튼이 있습니다.

public ObservableCollection<string> TestComboItemsSource { get; private set; } 

    public MyConstructor() 
    { 
     TestComboItemsSource = new ObservableCollection<string>(new []{ "items", "all", "umbrella", "watch", "coat" }); 
    } 

    private string _testComboItemsSourceSelected; 
    public string TestComboItemsSourceSelected 
    { 
     get { return _testComboItemsSourceSelected; } 
     set 
     { 
      if (value == "all") 
      { 
       TestComboItemsSourceSelected = "items"; 
       return; 
      } 

      _testComboItemsSourceSelected = value; 
      PropertyChanged(this, new PropertyChangedEventArgs(TestComboItemsSourceSelected)) 
     } 
    } 

    private ICommand _doStuffCommand; 

    public ICommand DoStuffCommand 
    { 
     get 
     { 
      return _doStuffCommand ?? (_doStuffCommand = new RelayCommand(p => 
                       { 
                        TestComboItemsSourceSelected = "items"; 
                       })); } 
    } 

확인을, 그래서 콤보 상자는 사용자가 항목 "모두"를 선택 할 때마다 항목 "항목"을 선택하고 싶지 :

<Button Command="{Binding DoStuffCommand}">Do stuff</Button> 

나는 나의 뷰 모델이 있습니다. 단추를 사용하여 콤보 상자의 SelectedItem을 업데이트 할 수 있으며 UI에 반영된 것을 볼 수 있습니다.

TestComboItemsSourceSelected 속성의 내 setter에서 viewModel을 업데이트하는 비슷한 논리가 있습니다. 사용자가 "all"을 선택한 경우 대신 SelectedItem을 "items"로 설정합니다. 코드별로, viewmodel 속성이 변경되지만 어떤 이유로이 속성이 UI에 반영되지 않습니다. 내가 놓친 게 있니? 내가 구현 한 방식의 부작용이 있습니까?

답변

1

다른 변경이 진행되는 동안 속성을 변경했기 때문입니다. WPF는이 속성을 설정하는 동안 PropertyChanged 이벤트를 수신하지 않습니다.

는이 문제를 해결하려면, 당신은 그것이 현재의 변화 완료 후 실행할 수 있도록 "예약"발송자와 새로운 변화는 수

public string TestComboItemsSourceSelected 
{ 
    get { return _testComboItemsSourceSelected; } 
    set 
    { 
     if (value == "all") 
     { 
      Application.Current.Dispatcher.BeginInvoke(new Action(() => { 
       TestComboItemsSourceSelected = "items"; 
      })); 
      return; 
     } 

     _testComboItemsSourceSelected = value; 
     PropertyChanged(this, new PropertyChangedEventArgs(TestComboItemsSourceSelected)) 
    } 
} 
+0

고마워요! 이런 생각이 나는 것 같아. – user832747

1

당신이 설명하는 동작은 매우 이상한 것 같다 나,하지만 "모두 선택"기능을 원할 경우, 표준적인 방법은 항목에 CheckBox가있는 콤보 상자를 만드는 것입니다.

각 항목은 작은 ViewModel (기본적으로 Id, Name 및 IsChecked 속성)으로 표시되며 ObservableCollection에 먼저 추가 된 모든 항목 선택을 수동으로 만들고 해당 PropertyChanged에 가입하여 해당 항목을 설정합니다. IsChecked 속성을 true로 설정합니다.