如何按类型获取 WPF 容器的子项? [英] How to get children of a WPF container by type?

查看:19
本文介绍了如何按类型获取 WPF 容器的子项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在WPF的MyContainer Grid中获取ComboBox类型的子控件?

How can I get the child controls of type ComboBox in MyContainer Grid in 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>

这一行给了我一个错误:

This line gives me an error:

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

推荐答案

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

This extension method will search recursively for child elements of the desired type:

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().

So using that you can ask for MyContainer.GetChildOfType<ComboBox>().

这篇关于如何按类型获取 WPF 容器的子项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆