Find all controls in WPF Window by type

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

    To get a list of all childs of a specific type you can use:

    private static IEnumerable FindInVisualTreeDown(DependencyObject obj, Type type)
    {
        if (obj != null)
        {
            if (obj.GetType() == type)
            {
                yield return obj;
            }
    
            for (var i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                foreach (var child in FindInVisualTreeDown(VisualTreeHelper.GetChild(obj, i), type))
                {
                    if (child != null)
                    {
                        yield return child;
                    }
                }
            }
        }
    
        yield break;
    }
    

提交回复
热议问题