从组合框 WPF 中获取所选项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39926155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:56:09  来源:igfitidea点击:

Get selected item from combobox WPF

c#wpfxamlcombobox

提问by Joozty

How can I get selected value from combobox in c#?

如何从 C# 的组合框中获取选定的值?

I tried somthing like this:

我试过这样的事情:

XAML

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#

C#

private void comboBox_SelectionChanged_1(object sender, 
    System.Windows.Controls.SelectionChangedEventArgs e)

    {
        MessageBox.Show(comboBox.SelectedValue.ToString());

    }

Message box shows me this System.Windows.Controls.ComboboxItem: Item2

消息框向我显示了这个System.Windows.Controls.ComboboxItem: Item2

I need only to show Item2

我只需要显示Item2

How can I do this?

我怎样才能做到这一点?

Thanks

谢谢

回答by haindl

You need to get the ComboBoxItemfrom the SelectedItemand cast the Content(in your case) to a string:

您需要获得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);
}