Find all controls in WPF Window by type

后端 未结 17 1227
春和景丽
春和景丽 2020-11-21 10:14

I\'m looking for a way to find all controls on Window by their type,

for example: find all TextBoxes, find all controls implementing specific i

17条回答
  •  被撕碎了的回忆
    2020-11-21 10:51

    The accepted answer returns the discovered elements more or less unordered, by following the first child branch as deep as possible, while yielding the discovered elements along the way, before backtracking and repeating the steps for not yet parsed tree branches.

    If you need the descendent elements in descending order, where the direct children will be yielded first, then their children and so on, the following algorithm will work:

    public static IEnumerable GetVisualDescendants(DependencyObject parent, bool applyTemplates = false)
        where T : DependencyObject
    {
        if (parent == null || !(child is Visual || child is Visual3D))
            yield break;
    
        var descendants = new Queue();
        descendants.Enqueue(parent);
    
        while (descendants.Count > 0)
        {
            var currentDescendant = descendants.Dequeue();
    
            if (applyTemplates)
                (currentDescendant as FrameworkElement)?.ApplyTemplate();
    
            for (var i = 0; i < VisualTreeHelper.GetChildrenCount(currentDescendant); i++)
            {
                var child = VisualTreeHelper.GetChild(currentDescendant, i);
    
                if (child is Visual || child is Visual3D)
                    descendants.Enqueue(child);
    
                if (child is T foundObject)
                    yield return foundObject;
            }
        }
    }
    

    The resulting elements will be ordered from nearest to farthest. This will be useful e.g. if you are looking for the nearest child element of some type and condition:

    var foundElement = GetDescendants(someElement)
                           .FirstOrDefault(o => o.SomeProperty == SomeState);
    

提交回复
热议问题