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

DeveloperDan picture DeveloperDan · Sep 15, 2010 · Viewed 64.4k times · Source

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.

Answer

Andy picture Andy · Sep 16, 2010
<ComboBox 
  Name="cboPickOne"
  SelectedValuePath="Content"
  >
  <ComboBoxItem>This</ComboBoxItem>
  <ComboBoxItem>should be</ComboBoxItem>
  <ComboBoxItem>easier!</ComboBoxItem>
</ComboBox>

In code:

   stringValue = cboPickOne.SelectedValue.ToString()