views:

59

answers:

4

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.

A: 

If you already know the content of your ComboBoxItem are only going to be strings, just access the content as string:

string text = ((ComboBoxItem)cboPickOne.SelectedItem).Content.ToString();
Jim Brissom
A: 
var s = (string)((ComboBoxItem)cboPickOne.SelectedItem).Content;

Dim s = DirectCast(DirectCast(cboPickOne.SelectedItem, ComboBoxItem).Content, String)

Since we know that the content is a string, I prefer a cast over a ToString() method call.

Heinzi
A: 

Just to clarify Heinzi and Jim Brissom's answers here is the code in Visual Basic:

Dim text As String = DirectCast(cboPickOne.SelectedItem, ComboBoxItem).Content.ToString()

and C#:

string text = ((ComboBoxItem)cboPickOne.SelectedItem).Content.ToString();

Thanks!

DeveloperDan
It depends though on whether you specify the items explicitly as ComboBoxItems or through bindings directly as strings. In the latter case `.Content` would throw an exception I think.
Alex Paven
A: 
<ComboBox 
  Name="cboPickOne"
  SelectedValuePath="Content"
  >
  <ComboBoxItem>This</ComboBoxItem>
  <ComboBoxItem>should be</ComboBoxItem>
  <ComboBoxItem>easier!</ComboBoxItem>
</ComboBox>

In code:

   stringValue = cboPickOne.SelectedValue.ToString()
Andy
As much as I'd like it to be that clean and simple, that alone doesn't work. SelectedValue returns a ComboBoxItem, not the string value I'm looking for. Placing ToString after SelectedValue returns this System.Windows.Controls.ComboBoxItem: followed by the selected text.
DeveloperDan
OK. I see you've added SelectedValuePath="Content" as an attribute to the ComboBox. That works! No ugly casting required. It's nice, clean and simple - just what I wanted. Thanks Andy!
DeveloperDan
You can also bind to SelectedValue.Content as the path, this decouples the behavior of ComboBox from the requirement of the binding target.
Eugarps