简体   繁体   中英

Get wpf combobox selected value

How do I get the selected value (eg Option1 ) as a string from my example below. I've tried loads of suggestions on Google but can't get the string.

XAML:

<ComboBox x:Name="selectOption" Text="Select Option" 
                 SelectionChanged="selectOption_SelectionChanged" 
                 SelectedValue="{Binding VMselectedOption, Mode=TwoWay}" >
    <ComboBoxItem Name="cbb1">Option1</ComboBoxItem>
    <ComboBoxItem Name="cbb2">Option2</ComboBoxItem>
    <ComboBoxItem Name="cbb3">Option3</ComboBoxItem>
</ComboBox>

codebehind:

private void selectOption_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   var selectedValue = selectOption.SelectedValue; 
}

//elsewhere in code
var test = viewModel.VMselectedOption;

Both selectedValue and test return the string " System.Windows.Controls.ComboBoxItem: Option1 " and not " Option1 "

This should be really simple but I just cannot get this working or see what is wrong?

You should set SelectedValuePath="Content".

<ComboBox x:Name="selectOption" Text="Select Option" 
                 SelectionChanged="selectOption_SelectionChanged" 
                 SelectedValue="{Binding VMselectedOption, Mode=TwoWay}" 
                 SelectedValuePath="Content">
    <ComboBoxItem Name="cbb1">Option1</ComboBoxItem>
    <ComboBoxItem Name="cbb2">Option2</ComboBoxItem>
    <ComboBoxItem Name="cbb3">Option3</ComboBoxItem>
</ComboBox>

You shouldn't insert the combobox items manually. Set them by using ItemsSource .

Basically you should create a list of options (or objects representing options) and set them as ItemsSource , this way your SelectedItem will be exactly the option which is selected, not the automatically created wrapping ComboboxItem .

string Value="";
if(myComboBox.SelectedIndex>=0) 
  Value=((ComboBoxItem)myComboBox.SelectedItem).Content.ToString();

更新代码以获取comboboxItem的内容。

var selectedValue = ((ComboBoxItem)selectOption.SelectedItem).Content.ToString();

ComboBoxItem.Content的类型为Object,因此您需要自己转换项目。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM