单击另一个按钮时无法获得组合框选定的项目值

Tk1*_*993 2 c# wpf combobox exception

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

这是代码:

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

以下是例外情况:

System.InvalidCastException:"无法将'System.String'类型的对象强制转换为'System.Windows.Controls.ComboBoxItem'."

我已经经历过以下的一些链接:

无法获取ComboBox所选项目值

ComboBox- SelectionChanged事件具有旧值,而不是新值

从c#wpf中的组合框中获取选定的值

等等..

但没有得到解决方案.

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

suj*_*lil 6

通过使用.Content.ToString()整个事物转换为字符串,并且您试图将此结果字符串ComboBoxItem强制转换为此类转换是不允许的,但您可以将其转换SelectedItem为a ComboBoxItem然后从中获取值.尝试这样的事情:

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

如果您将这两个步骤组合在一起,就可以这样写:

string item =((ComboBoxItem)cmbOptions.SelectedItem).Content.ToString(); 
Run Code Online (Sandbox Code Playgroud)

附加说明:

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