Find all controls in WPF Window by type

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

    Small change to the recursion to so you can for example find the child tab control of a tab control.

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

提交回复
热议问题