我正在尝试检查我的组合框中的值,但它失败了,我的值从未匹配并且我收到此警告:
Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (((ComboBox)sender).SelectedValue == "Floyd-Warshall")
{
MessageBox.Show("foobar");
谢谢。
最佳答案
有多种修复方法,一种是转换为字符串,另一种是在 SelectedValue 上调用 ToString。
正如您所说的其他一些建议的答案不起作用,您确定组合框中的项目实际上是一个字符串吗?
例如,这将适用于建议的修复:
<Window x:Class="ExerciseOne.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" xmlns:extern="clr-namespace:System;assembly=mscorlib">
<Grid>
<ComboBox SelectionChanged="ComboBox_SelectionChanged">
<ComboBox.Items>
<extern:String>Hello</extern:String>
<extern:String>Floyd-Warshall</extern:String>
</ComboBox.Items>
</ComboBox>
</Grid>
</Window>
但这不会:
<Window x:Class="ExerciseOne.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" xmlns:extern="clr-namespace:System;assembly=mscorlib">
<Grid>
<ComboBox SelectionChanged="ComboBox_SelectionChanged">
<ComboBox.Items>
<ComboBoxItem>Hello</ComboBoxItem>
<ComboBoxItem>Floyd-Warshall</ComboBoxItem>
</ComboBox.Items>
</ComboBox>
</Grid>
</Window>
您可以通过在现有事件处理程序中运行以下代码来快速确定是否属于这种情况:
MessageBox.Show(((ComboBox)sender).SelectedValue.GetType().ToString());
关于c# - Combobox 和 SelectionChanged 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6083689/