2011-09-12 4 views
2

WPF에서 만든 ComboBox의 선택 영역을 기반으로 작업을 시작하려고합니다. 나는 WPF와 C#에 익숙하지 않다. 내 콤보 상자은 NameList 뒤에 코드의 목록 속성이다WPF에서 ComboBox의 항목을 선택하여 작업 수행

<ComboBox x:Name="SampleComboBox" Width="100" ItemsSource="{Binding Path=NameList}" /> 

있습니다. 이제 ComboBox의 선택을 기반으로 액션을 생성하고 어디에서 시작해야할지 모르겠습니다. 감사.

답변

2

SelectionChanged 이벤트를 처리 할 방법을 추가해야합니다. 당신은 코드에서이 작업을 수행 할 수 있습니다 :

this.MyComboBox.SelectionChanged += new SelectionChangedEventHandler(OnSelectionChanged); 

또는 XAML에서

:

<ComboBox x:Name="SampleComboBox" Width="100" 
ItemsSource="{Binding Path=NameList}" SelectionChanged="OnSelectionChanged" /> 

그런 다음 선택한 항목 뭔가 할 수있는 곳 :

private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    ComboBoxItem cbi = (ComboBoxItem) (sender as ComboBox).SelectedItem; 
} 
0

SampleComboBox.SelectedItem을 작성하여 선택한 개체를 가져올 수 있습니다.
소스 목록에있는 항목의 인스턴스를 반환합니다.

0

이 NameList의 ItemsSource 인 값의 유한 집합입니까? 같은 것을 가지고, 이것에 대한 당신의 ViewModel에서 다음

<ComboBox x:Name="SampleComboBox" Width="100" SelectedItem="{Binding TheItem}" ItemsSource="{Binding Path=NameList}" /> 

과 :

왜 읽고 그 XAML을 수정하지

public static readonly DependencyProperty TheItemProperty= 
    DependencyProperty.Register("TheItem", typeof(string), typeof(OrderEditorViewModel), 
     new PropertyMetadata((s, e) => { 
      switch (e.NewValue) { 
       case "SomeValue": 
        // Do something 
        break; 
       case "SomeOtherValue": 
        // Do another thing 
        break; 
       default: 
        // Some default action 
        break; 
      } 
    })); 

public string TheItem{ 

    get { return (string)GetValue(TheItemProperty); } 
    set { SetValue(TheItemProperty, value); } 
} 

을 할 수 있습니다 않는 스위치의 선택에 따라 행동 선택이 변경 될 때마다 호출되는 명령문.

관련 문제