【问题标题】:Cannot get combobox selected item value on click of another button单击另一个按钮时无法获取组合框选定项的值
【发布时间】:2017-02-01 07:34:15
【问题描述】:

我有一个组合框 cmbOptions 和一个按钮 btnShowItem

这是代码:

private void btnShowItem_click(object sender, RoutedEventArgs e)
{
    string item = ((ComboBoxItem)cmbOptions.SelectedItem).Content.ToString(); //Exception is here
}

以下是例外:

System.InvalidCastException:“无法将 'System.String' 类型的对象转换为 'System.Windows.Controls.ComboBoxItem' 类型。”

我已经浏览过很多这样的链接:

Cannot get ComboBox selected item value

ComboBox- SelectionChanged event has old value, not new value

Get selected value from combo box in c# wpf

等等等等。

但没有得到解决方案。

请注意,我需要在 buttonclick 上获取 comboboxItem 的值,而不是在 cmbSelectionChange 事件上

【问题讨论】:

  • 您是在使用绑定还是手动添加了几个ComboBoxItems?
  • @ManfredRadlwimmer 手动

标签: c# wpf exception combobox


【解决方案1】:

通过使用.Content.ToString(),整个东西都被转换为字符串,并且您试图将此结果字符串转换为ComboBoxItem,不允许这种转换,但是您可以将SelectedItem转换为ComboBoxItem,然后从他们那里获取价值。试试这样的:

ComboBoxItem currentItem = (ComboBoxItem)cmbOptions.SelectedItem; // this will be the comboBoxItem
string item =currentItem.Content.ToString(); // gives you the required string

如果你把这两个步骤结合起来,你可以这样写:

string item =((ComboBoxItem)cmbOptions.SelectedItem).Content.ToString(); 

补充说明:

仍然,您得到相同的异常意味着SelectedItem 将是一个字符串,尝试获取这样的值:string item = cmbOptions.SelectedItem.ToString(),这会发生,因为您可以分配DisplayMemberPath

【讨论】:

  • @Tushar:请你看看更新
  • 正如我已经说过的兄弟,同样的上述异常正在发生,我写的代码和你回答的代码都是一样的
  • 试试这个string item = cmbOptions.SelectedItem.ToString() 并查看我帖子中的附加说明
【解决方案2】:
        for (int x = 0; x < cboType.Items.Count; x++)
        {
            cboType.SelectedIndex = x;
            var typeCombo = ((ComboBox)cboType);
            var valueType = ((ComboBoxItem)typeCombo.SelectedValue);

            if (thisProductInfo.Type == valueType.Content.ToString())
            {
                cboType.SelectedIndex = x;
                break;
            }
        }

        //for (int x = 0; x < cboColor.Items.Count; x++)
        //{
        //    cboColor.SelectedIndex = x;
        //    var colorCombo = ((ComboBox)cboColor);
        //    var valueColor = ((ComboBoxItem)colorCombo.SelectedValue);

        //    if (thisProductInfo.Type == valueColor.Content.ToString())
        //    {
        //        cboColor.SelectedIndex = x;
        //        break;
        //    }
        //}

这个怎么样?前者有效,但注释循环给了我一个铸造错误,尝试了 selectedindex 但结果相同,只有前者有效。

【讨论】:

  • 您应该删除不工作(注释)块。或许你能解释一下“SelectedValue”和“SelectedItem”的区别?
  • 不,我是来找答案的,我不知道为什么下面的代码不起作用,而上面的代码却没有,但它们基本上是一样的......很奇怪......
猜你喜欢
  • 2020-02-28
  • 1970-01-01
  • 2015-01-08
  • 2020-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-24
相关资源
最近更新 更多