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.
Since we know that the content is a string, I prefer a cast over a
ToString()
method call.If you add items in ComboBox as
Then use this:
But if you add items by data binding, use this:
Just to clarify Heinzi and Jim Brissom's answers here is the code in Visual Basic:
and C#:
Thanks!
Using
cboPickOne.Text
should give you the string.If you already know the content of your ComboBoxItem are only going to be strings, just access the content as string:
In code: