Selecting an item in ComboBox in WPF to do an action
I'm trying to initiate an action based on a selection in a开发者_StackOverflow ComboBox I created in WPF. I'm pretty new to WPF and C#. My ComboBox has
<ComboBox x:Name="SampleComboBox" Width="100" ItemsSource="{Binding Path=NameList}" />
Where NameList is a List property in the code behind. Now I want to generate an action based on the selection in the ComboBox and not sure where to start. Thanks.
You'll need to add a method to handle the SelectionChanged
event. You can either do this in code:
this.MyComboBox.SelectionChanged += new SelectionChangedEventHandler(OnSelectionChanged);
or in XAML:
<ComboBox x:Name="SampleComboBox" Width="100"
ItemsSource="{Binding Path=NameList}" SelectionChanged="OnSelectionChanged" />
where you can then do something with the selected items:
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBoxItem cbi = (ComboBoxItem) (sender as ComboBox).SelectedItem;
}
You can get the selected object by writing SampleComboBox.SelectedItem
.
This will return an instance of an item in your source list.
Are these a finite set of values in this NameList that is the ItemsSource for this?
Why not amend that xaml to read:
<ComboBox x:Name="SampleComboBox" Width="100" SelectedItem="{Binding TheItem}" ItemsSource="{Binding Path=NameList}" />
and then in your ViewModel for this, have something like:
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); }
}
You can do your actions based on the selection in that switch statement which will be invoked whenever the selection is changed.
精彩评论