我有一个组合框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'。”
我已经看过许多这样的链接:
ComboBox- SelectionChanged事件具有旧值,而不是新值
等,等等。
但没有得到解决方案。
请注意,我只需要在buttonclick上获取comboboxItem的值,而不能在cmbSelectionChange事件上获取
通过使用.Content.ToString()
整个对象将转换为字符串,并且您试图将结果字符串ComboBoxItem
转换为这种转换是不允许的,但是您可以将SelectedItem
a转换为a 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句