一尘不染

如何按类型获取WPF容器的子代?

c#

我怎样才能类型的子控件ComboBoxMyContainer Grid的WPF?

<Grid x:Name="MyContainer">                    
    <Label Content="Name"  Name="label1"  />
    <Label Content="State" Name="label2"  />
    <ComboBox Height="23" HorizontalAlignment="Left" Name="comboBox1"/>
    <ComboBox Height="23" HorizontalAlignment="Left" Name="comboBox3" />
    <ComboBox Height="23" HorizontalAlignment="Left" Name="comboBox4" />
</Grid>

这行给我一个错误:

var myCombobox = this.MyContainer.Children.GetType(ComboBox);

阅读 429

收藏
2020-05-19

共1个答案

一尘不染

此扩展方法将递归搜索所需类型的子元素:

public static T GetChildOfType<T>(this DependencyObject depObj) 
    where T : DependencyObject
{
    if (depObj == null) return null;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        var child = VisualTreeHelper.GetChild(depObj, i);

        var result = (child as T) ?? GetChildOfType<T>(child);
        if (result != null) return result;
    }
    return null;
}

因此,您可以要求使用MyContainer.GetChildOfType<ComboBox>()

2020-05-19