现在我正在尝试在WPF中实现Combobox。当我首先选择组合框时,我得到了一个空值。
第二次开始,我在组合中获得了先前选择的值。
1st - Empty - When I select Candy
2nd - Candy - when I select Frog
....
....
当我选择糖果时,如何获得组合框选择的值 - 值也想成为糖果。
我的代码
<ComboBox Height="23" HorizontalAlignment="Left" Margin="674,14,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" SelectionChanged="comboBox1_SelectionChanged">
<ComboBoxItem Content="Candy" />
<ComboBoxItem Content="Edge" />
<ComboBoxItem Content="Frog" />
<ComboBoxItem Content="Inc" />
<ComboBoxItem Content="Mercury" />
<ComboBoxItem Content="Metal" />
<ComboBoxItem Content="Sleek" />
</ComboBox>
我的 C# 代码
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MessageBox.Show("" + comboBox1.Text);
}
试试这个
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MessageBox.Show("" + ((ComboBoxItem)comboBox1.SelectedValue).Content);
}
每个组合框项目都有内容,所以如果你想要选定的项目,请尝试下面的代码,。
if (comboBox1.SelectedItem != null)
{
ComboBoxItem cbItem = (ComboBoxItem) comboBox1.SelectedItem;
MessageBox.Show(cbItem.Content.ToString());
}
我希望它能得到充分的帮助,如果它有助于接受我的答案。