2011-09-12 11 views
2

WPFで作成したコンボボックスの選択に基づいてアクションを開始しようとしています。私はWPFとC#でかなり新しいです。私のコンボボックスはWPFでコンボボックスのアイテムを選択してアクションを実行する

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

です。ここで、NameListはコードビハインドのListプロパティです。今私は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である値の有限集合ですか?

なぜ読むためにそのXAMLを修正していない。このため、あなたのViewModelで

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

、その後を、のようなものがあります。

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

をあなたはそのスイッチで選択に基づいて、あなたのアクションを行うことができます選択が変更されたときに呼び出されるステートメント。

関連する問題