无法在ComboBox中获取选定的文本或值

时间:2015-11-18 10:35:28

标签: c# wpf

我的wpf应用程序中有一个包含三个项目的combox:

<ComboBoxItem Tag="some value">Text</ComboBoxItem>
<ComboBoxItem Tag="some value2">Text2</ComboBoxItem>
<ComboBoxItem Tag="some value3">Text3</ComboBoxItem>

我想在运行时获取选定的文本或值。当我这样做时:

myComboBox.SelectedValue.ToString()

它返回:

System.Windows.Controls.ComboBoxItem: Text2

如何获取所选文本或值?

4 个答案:

答案 0 :(得分:2)

因为您需要Content ComboBoxItem属性,所以您应该尝试这样:

(myComboBox.SelectedValue as ComboBoxItem).Content.ToString();

Tag

(myComboBox.SelectedValue as ComboBoxItem).Tag.ToString();

答案 1 :(得分:1)

您需要将Combobox的SelectedItem属性强制转换为对象,然后才能访问属性。因此,在您的情况下,您需要将其强制转换为ComboBoxItem。

答案 2 :(得分:0)

您只需要从对象中获取标记。

<ComboBox SelectionChanged="Selector_OnSelectionChanged">
    <ComboBoxItem Tag="some value">Text</ComboBoxItem>
    <ComboBoxItem Tag="some value2">Text2</ComboBoxItem>
    <ComboBoxItem Tag="some value3">Text3</ComboBoxItem>
</ComboBox>

    private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var cb = sender as ComboBox;
        if (cb == null)
        {
            return;
        }

        var selectedItem = cb.SelectedValue as ComboBoxItem;
        if (selectedItem == null)
        {
            return;
        }

        var tag = selectedItem.Tag;

        Debug.WriteLine(tag);  
    }

答案 3 :(得分:-1)

试试这个

<ComboBox Name="comboBox" SelectedValuePath="Content">
  <ComboBoxItem>text</ComboBoxItem>
  <ComboBoxItem>here</ComboBoxItem>
  <ComboBoxItem>text</ComboBoxItem>
</ComboBox>

获取值

 var value = comboBox.SelectedValue.ToString()