【问题标题】:C# UWP how to get the value of changed ComboBoxItemC# UWP如何获取更改后的ComboBoxItem的值
【发布时间】:2017-09-07 10:41:03
【问题描述】:

在我的 .xaml 文件中,我的组合框如下:

<ComboBox Name="CLengthCombo" SelectionChanged="ComboBox_SelectionChanged"> <ComboBoxItem Content="24"/> <ComboBoxItem Content="25"/> <ComboBoxItem Content="26" IsSelected="True"/> <ComboBoxItem Content="27"/> </ComboBox> 如何实现我的 ComboBox_SelectionChanged 事件,以便在应用程序运行时获取用户更改的 comboBoxItem 的内容?在这种情况下使用 SelectionChanged 事件是否正确?以下不起作用:

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { string chosenItem = CLengthCombo.PlaceholderText; } 在此先感谢您的帮助!

【问题讨论】:

    标签: c# combobox


    【解决方案1】:

    你可以这样做

    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                var comboBoxItem = e.AddedItems[0] as ComboBoxItem;
                if (comboBoxItem == null) return;
                var content = comboBoxItem.Content as string;
                if (content != null && content.Equals("some text"))
                {
                    //do what ever you want
                }
            }
    

    【讨论】:

    • 您可以将其作为有效答案进行检查:)
    【解决方案2】:

    您可以使用组合框的 SelectedItem 属性

    (CLengthCombo.SelectedItem as ComboBoxItem).Content
    

    https://msdn.microsoft.com/library/windows/apps/windows.ui.xaml.controls.combobox.aspx#properties

    【讨论】:

    • 感谢 bhmahler 的提示!
    【解决方案3】:

    让你的组合框来工作,c.(...) 有 SelectedItem, SelectedText ...:

    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var c = sender as ComboBox;
    
        var item = c.(...);
    }
    

    【讨论】:

    • 请对代码进行一些解释,对你来说显而易见的东西对其他人可能并不明显
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 2011-08-13
    相关资源
    最近更新 更多