What is the simplest way to get the selected text

2019-03-11 17:34发布

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.

8条回答
\"骚年 ilove
2楼-- · 2019-03-11 18:01
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.

查看更多
一夜七次
3楼-- · 2019-03-11 18:07

If you add items in ComboBox as

youComboBox.Items.Add("Data"); 

Then use this:

youComboBox.SelectedItem; 

But if you add items by data binding, use this:

DataRowView vrow = (DataRowView)youComboBox.SelectedItem;
DataRow row = vrow.Row;
MessageBox.Show(row[1].ToString());
查看更多
倾城 Initia
4楼-- · 2019-03-11 18:14

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!

查看更多
手持菜刀,她持情操
5楼-- · 2019-03-11 18:14

Using cboPickOne.Text should give you the string.

查看更多
等我变得足够好
6楼-- · 2019-03-11 18:15

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();
查看更多
三岁会撩人
7楼-- · 2019-03-11 18:19
<ComboBox 
  Name="cboPickOne"
  SelectedValuePath="Content"
  >
  <ComboBoxItem>This</ComboBoxItem>
  <ComboBoxItem>should be</ComboBoxItem>
  <ComboBoxItem>easier!</ComboBoxItem>
</ComboBox>

In code:

   stringValue = cboPickOne.SelectedValue.ToString()
查看更多
登录 后发表回答