13

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?

  • Similar question here https://stackoverflow.com/questions/3721430/what-is-the-simplest-way-to-get-the-selected-text-of-a-combo-box-containing-only the top answer worked great for me. – SendETHToThisAddress Jan 14 '21 at 01:43

5 Answers5

21

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>
Supitchaya
  • 491
  • 5
  • 6
13

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.

Vlad
  • 33,616
  • 5
  • 74
  • 185
8
string Value="";
if(myComboBox.SelectedIndex>=0) 
  Value=((ComboBoxItem)myComboBox.SelectedItem).Content.ToString();
Anatoly Nikolaev
  • 450
  • 2
  • 12
  • It is better to check: if (((ComboBoxItem)myComboBox.SelectedItem).Content != null). Because if you use IsSelected="True" for some element the Content will be null after initialization. – Sasha Feb 23 '17 at 15:09
7

Update your code to get the Content of comboboxItem.

var selectedValue = ((ComboBoxItem)selectOption.SelectedItem).Content.ToString();
Nitin
  • 17,418
  • 2
  • 33
  • 51
2

ComboBoxItem.Content is of type Object, so you'll need to cast the item yourself.

Daniel
  • 10,191
  • 22
  • 79
  • 110