2011-09-12 38 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閱讀:

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

你可以做基於開關中選擇你的行動當選擇被改變時將被調用的語句。

相關問題