Find all controls in WPF Window by type

后端 未结 17 1668
春和景丽
春和景丽 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:37

    Use the helper classes VisualTreeHelper or LogicalTreeHelper depending on which tree you're interested in. They both provide methods for getting the children of an element (although the syntax differs a little). I often use these classes for finding the first occurrence of a specific type, but you could easily modify it to find all objects of that type:

    public static DependencyObject FindInVisualTreeDown(DependencyObject obj, Type type)
    {
        if (obj != null)
        {
            if (obj.GetType() == type)
            {
                return obj;
            }
    
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject childReturn = FindInVisualTreeDown(VisualTreeHelper.GetChild(obj, i), type);
                if (childReturn != null)
                {
                    return childReturn;
                }
            }
        }
    
        return null;
    }
    

提交回复
热议问题