wpfcomboboxselecteditemselectedvalueselectedtext

What is the simplest way to get the selected text of a combo box containing only text entries?


My WPF ComboBox contains only text entries. The user will select one. What is the simplest way to get the text of the selected ComboBoxItem? Please answer in both C# and Visual Basic. Here is my ComboBox:

<ComboBox Name="cboPickOne">
    <ComboBoxItem>This</ComboBoxItem>
    <ComboBoxItem>should be</ComboBoxItem>
    <ComboBoxItem>easier!</ComboBoxItem>
</ComboBox>

By the way, I know the answer but it wasn't easy to find. I thought I'd post the question to help others. REVISION: I've learned a better answer. By adding SelectedValuePath="Content" as a ComboBox attribute I no longer need the ugly casting code. See Andy's answer below.


Solution

  • In your XAML add SelectedValuePath="Content"

    <ComboBox Name="cboPickOne" SelectedValuePath="Content">
        <ComboBoxItem>This</ComboBoxItem>
        <ComboBoxItem>should be</ComboBoxItem>
        <ComboBoxItem>easier!</ComboBoxItem>
    </ComboBox>
    

    This way when you use .SelectedValue.ToString() in the C# code it will just get the string value without all the extra junk:

    stringValue = cboPickOne.SelectedValue.ToString()