【问题标题】:Looping through all comboboxes in wpf [duplicate]循环遍历wpf中的所有组合框[重复]
【发布时间】:2015-04-05 09:55:58
【问题描述】:

我正在尝试创建一个简单的 WPF 应用程序,它只有组合框和提交按钮。
我想做的是,
当我点击按钮时,
我的函数应该遍历所有组合框并获取它们的内容。

我的 XAML -

<ComboBox HorizontalAlignment="Left" Name="ComboBox2"  > // the name goes from 2 to 50
  <ComboBoxItem  IsSelected="True">Y</ComboBoxItem>
  <ComboBoxItem>N</ComboBoxItem>
  <ComboBoxItem>NA</ComboBoxItem>
</ComboBox>

这是我的点击功能

private void Submit(object sender, RoutedEventArgs e)
        {
            LinkedList<String> allnos = new LinkedList<string>();
            for (int i = 2; i < 12; i++)
            {
                ComboBoxItem Item = (ComboBoxItem)Combobox+"i"+.SelectedItem; // this will not work, how should i get it?
                allnos.AddLast(Item.Content);
            }
        }

如何遍历所有组合框以获取选定的值?? 感谢您的建议。

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    假设您的所有组件都在某个父组件中,您可以这样做:

    foreach(UIElement element in parent.Children)
    {
        if(element is ComboBox)
        {
            ComboBox cb = (ComboBox)element;
            ComboBoxItem Item = cb.SelectedItem; 
            allnos.AddLast(Item.Content);
        }
    }
    

    【讨论】:

    • 一个简单的 linq 查询应该完成所有工作: var contents = (from child in Grid.Children.OfType() select ((ComboBoxItem) child.SelectedItem).Content).ToList( );
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 2018-12-11
    • 2012-11-03
    • 2014-07-14
    • 2013-09-12
    • 1970-01-01
    相关资源
    最近更新 更多