我正在尝试创建一个包含不同选项的组合框,并在选择选项时触发不同的方法。但是当我运行应用程序并选择一个选项时,没有任何反应。以下是代码片段:
<ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="10,84,0,0" VerticalAlignment="Top" Width="100" SelectionChanged="comboBox_SelectionChanged" SelectedItem="{Binding Path=index, Mode=TwoWay}" SelectedValuePath="Tag">
<ComboBoxItem Content="Kilograms" Tag="0"></ComboBoxItem>
<ComboBoxItem Content="Pounds" Tag="1"></ComboBoxItem>
</ComboBox>
private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox Selector = (sender as ComboBox);
int index = Selector.SelectedIndex;
switch(Selector.ToString())
{
case "0":
workOutKilo();
break;
case "1":
break;
}
}
private void workOutPounds()
{
MessageBox.Show("This is the pounds conversion");
}
private void workOutKilo()
{
MessageBox.Show("This is the kilo conversion");
}
如何在设置组合框中的选项并将消息显示到屏幕时运行方法?
答案 0 :(得分:1)
不要将发件人对象用作switch
条件。而是使用获取的索引:
private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var comboBox = sender as ComboBox;
int index = comboBox.SelectedIndex;
switch (index)
{
case 0:
workOutKilo();
break;
case 1:
workOutPounds();
break;
}
}
您当前的代码不起作用,因为调用ComboBox对象上的ToString
方法会生成以下文本:System.Windows.Controls.ComboBox Items.Count:2
,既不是字符串"0"
,也不是字符串{{ 1}}。