如何从c#中的组合框中获取选定的值?
我试过这样的事情:
XAML
<ComboBox x:Name="comboBox" SelectionChanged="comboBox_SelectionChanged_1" >
<ComboBoxItem Name="Brno" IsSelected="True" Content="Brno"/>
<ComboBoxItem Name="Item2" Content="Item2"/>
<ComboBoxItem Name="Item3" Content="Item3"/>
</ComboBox>
C#
private void comboBox_SelectionChanged_1(object sender,
System.Windows.Controls.SelectionChangedEventArgs e)
{
MessageBox.Show(comboBox.SelectedValue.ToString());
}
消息框显示我 System.Windows.Controls.ComboboxItem:Item2
我只需要显示 Item2
我该怎么做?
由于
答案 0 :(得分:3)
您需要从ComboBoxItem
获取SelectedItem
并将Content
(在您的情况下)转换为string
:
private void comboBox_SelectionChanged_1(object sender,
System.Windows.Controls.SelectionChangedEventArgs e)
{
string content = ((ComboBoxItem)comboBox.SelectedItem).Content as string;
if (content != null)
MessageBox.Show(content);
}