Get wpf combobox selected value

后端 未结 5 990
无人及你
无人及你 2021-02-13 17:53

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.

相关标签:
5条回答
  • 2021-02-13 18:15

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

    0 讨论(0)
  • 2021-02-13 18:23

    Update your code to get the Content of comboboxItem.

    var selectedValue = ((ComboBoxItem)selectOption.SelectedItem).Content.ToString();
    
    0 讨论(0)
  • 2021-02-13 18:27

    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.

    0 讨论(0)
  • 2021-02-13 18:36

    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>
    
    0 讨论(0)
  • 2021-02-13 18:38
    string Value="";
    if(myComboBox.SelectedIndex>=0) 
      Value=((ComboBoxItem)myComboBox.SelectedItem).Content.ToString();
    
    0 讨论(0)
提交回复
热议问题