从combobox WPF中获取所选项目

时间:2016-10-07 21:37:10

标签: c# wpf xaml combobox

如何从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

我该怎么做?

由于

1 个答案:

答案 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);
}