XAML .Children 属性 问题

XAML .Children property problems

我正在尝试过滤我的 .XAML 文件并为许多 ComboBox 设置 ItemSource。我遇到的问题是,当它到达 foreach 循环的底层时,我的 degugger 出错并显示一条明显的转换失败消息......这里有一些代码来澄清我到底是什么谈论:

XAML:

<StackPanel x:Name="spFruit" Orientation="Horizontal" HorizontalAlignment="Left">
    <StackPanel x:Name="spFruit1" Orientation="Vertical" Height="Auto"  Width="250">
        <StackPanel Orientation="Horizontal" Margin="0,2,0,0">
            <CheckBox x:Name="cbApple"  Content="Apples" Margin="0,5"></CheckBox>
            <Label Content="Quantity: " Margin="67,0,0,0"></Label>
            <ComboBox x:Name="cmbxApple"  Margin="10,0,0,0" Width="50" IsEnabled="{Binding ElementName=cbApple, Path=IsChecked}"></ComboBox>
        </StackPanel>
        <StackPanel Orientation="Horizontal" Margin="0,2,0,0">
            <CheckBox x:Name="cbApricot" Content="Apricots" Margin="0,5"></CheckBox>
            <Label Content="Quantity: " Margin="59,0,0,0"></Label>
            <ComboBox x:Name="cmbxApricot" Margin="10,0,0,0" Width="50" IsEnabled="{Binding ElementName=cbApricot, Path=IsChecked}"></ComboBox>
        </StackPanel>

等等等等...(有成千上万的项目,我们不需要检查所有项目。)现在,ComboBoxes...我最初是尝试用 List<int>(我已经填充)填充它们,如下所示:

C#

foreach (StackPanel spVert in spFruit.Children)
    foreach (StackPanel sp in spVert.Children)
        foreach (ComboBox cmbx in sp.Children)
            cmbx.ItemsSource = lstComboContent; 

现在,我认为(对于我的具体示例)这应该遍历最低 StackPanel (sp) 内的所有控件并找到 ComboBoxes,然后分配他们的 ItemSource。显然,我错了,因为当代码执行时,它立即在第一个 Checkbox 处停止并给我一个错误,它 Cannot Convert System.Windows.Controls.CheckBox to System.Windows.Controls.ComboBox

我的官方问题是这样的: 为什么循环不只是跳过 Checkbox?显然,Checkbox、Label 和 ComboBox 都是 StackPanel 的子项,如果我告诉循环专门查找 ComboBox,为什么它会停止(而不是继续经过)Checkbox?

我对XAML还是很陌生,所以请原谅我的无知。我以为我对它有一个体面的理解,直到遇到这个问题。挂断电话似乎是一件小事,但我在这里。感谢所有的帮助和反馈。

问题出在这里:

foreach (ComboBox cmbx in sp.Children)
    cmbx.ItemsSource = lstComboContent; 

StackPanel 有 3 childrens - CheckBox, Label, ComboBox。在您的 for 循环中,您遍历了所有 children,但您尝试将每个 child 转换为 ComboBox。首先 child 是 CheckBox,你不能将它转换为 ComboBox。您的代码应该是:

foreach (StackPanel spVert in spFruit.Children)
    foreach (StackPanel sp in spVert.Children)
        foreach (var control in sp.Children)
        {
            if (control.GetType() == typeof (ComboBox))
            {
                ((ComboBox)control).ItemsSource = lstComboContent;
            }
        }