45

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

<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);
4

6 回答 6

94

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

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

于 2012-04-23T10:56:09.143 回答
45

Children 是 UIElements 的集合。因此,您需要遍历项目并确定每个项目是否属于所需类型。幸运的是,已经有一个 Linq 方法可以做到这一点,即Enumerable.OfType<T>,您可以使用扩展方法语法方便地调用它:

var comboBoxes = this.MyContainer.Children.OfType<ComboBox>();

此方法根据集合的类型过滤集合,并在您的情况下仅返回 type 的元素ComboBox

如果您只想要第一个 ComboBox (正如您的变量名称所暗示的那样),您只需将调用附加FirstOrDefault()到查询:

var myComboBox = this.MyContainer.Children.OfType<ComboBox>().FirstOrDefault();
于 2012-04-23T10:52:01.747 回答
9

所有这些答案,但一个使用递归,IMO只是蹩脚:)

获得视觉孩子:

public static IEnumerable<T> FindVisualChildren<T>([NotNull] this DependencyObject parent) where T : DependencyObject
{
    if (parent == null)
        throw new ArgumentNullException(nameof(parent));

    var queue = new Queue<DependencyObject>(new[] {parent});

    while (queue.Any())
    {
        var reference = queue.Dequeue();
        var count = VisualTreeHelper.GetChildrenCount(reference);

        for (var i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(reference, i);
            if (child is T children)
                yield return children;

            queue.Enqueue(child);
        }
    }
}

获取逻辑孩子:

public static IEnumerable<T> FindLogicalChildren<T>([NotNull] this DependencyObject parent) where T : DependencyObject
{
    if (parent == null)
        throw new ArgumentNullException(nameof(parent));

    var queue = new Queue<DependencyObject>(new[] {parent});

    while (queue.Any())
    {
        var reference = queue.Dequeue();
        var children = LogicalTreeHelper.GetChildren(reference);
        var objects = children.OfType<DependencyObject>();

        foreach (var o in objects)
        {
            if (o is T child)
                yield return child;

            queue.Enqueue(o);
        }
    }
}

请注意,两个深度遍历树,如果您希望在第一次遇到时停止,则更改两个代码以将调用包含queue.Enqueue在一个else块中。

于 2018-09-16T21:39:20.287 回答
3

所有这些答案都非常好,但是,如果你试图找到一个特定的 T 类型的视觉孩子,你要么被困住,然后找到你想要的,要么希望你得到的第一个是一个你想要的。我合并了几种方法以根据标准找到特定的方法。它有点像 LINQ,但我不想尝试处理递归枚举器。

像这样使用它:

MyContainer.FirstOrDefaultChild<Label>(l => l.Content=="State")

我把它写成一个扩展方法。

public static class DependencyObjectExtensions
{
    public static T FirstOrDefaultChild<T>(this DependencyObject parent, Func<T, bool> selector) 
        where T : DependencyObject
    {
        T foundChild;
        return FirstOrDefaultVisualChildWhere(parent, selector, out foundChild) ? foundChild : default(T);
    }

    private static bool FirstOrDefaultVisualChildWhere<T>(DependencyObject parent, Func<T, bool> selector,
        out T foundChild) where T : DependencyObject
    {
        var count = VisualTreeHelper.GetChildrenCount(parent);
        for (var i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            var tChild = child as T;
            if (tChild != null)
            {
                if (!selector(tChild)) continue;
                foundChild = tChild;
                return true;
            }

            if (FirstOrDefaultVisualChildWhere(child, selector, out foundChild))
            {
                return true;
            }
        }
        foundChild = default(T);
        return false;
    }
于 2018-04-18T21:04:29.060 回答
2

搜索包含预定点(屏幕)的特定类型的第一个子项:

(参数'point'是调用'PointToScreen'函数的结果(以Visual类型声明))

private TDescendantType FindDescendant<TDescendantType>(DependencyObject parent, Point screenPoint) 
         where TDescendantType : DependencyObject
{
    int count = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < count; i++)
    {
        var child = VisualTreeHelper.GetChild(parent, i);
        if (child is Visual)
        {
            Point point = ((Visual)child).PointFromScreen(screenPoint);
            Rect rect = VisualTreeHelper.GetDescendantBounds((Visual)child);

            if (!rect.Contains(point))
                continue;
        }

        if (child is TDescendantType)
        {
            return (TDescendantType)child;
        }

        child = FindDescendant<TDescendantType>(child, screenPoint);
        if (child != null)
        {
            return (TDescendantType)child;
        }
    }
    return null;
}
于 2016-03-29T15:42:57.103 回答
-1

我找到了这个工作示例:

foreach (object o in LogicalTreeHelper.GetChildren(myWindow))
{
    if (o is SomeTypeOfMine)
    {
      //do something
    }
}

资料来源:https ://social.msdn.microsoft.com/Forums/vstudio/en-US/e0be708a-5fa2-4479-b5a0-8ff44a963803/find-all-child-controls-of-a-type?forum=wpf

于 2019-07-18T01:53:40.233 回答