Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

In your xml 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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...