C# – How to get all child controls with a given generic type T

This recursive function allows you to get all controls of a given generic type that are children of a given element in the VisualTree.


    public static IEnumerable<T> FindVisualChildren<T>(DependencyObject parent) 
        where T : DependencyObject
    {
        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);

            var childType = child as T;
            if (childType != null)
            {
                yield return (T)child;
            }

            foreach (var other in FindVisualChildren<T>(child))
            {
                yield return other;
            }
        }
    }

Share            
X
                                                                                                        

Leave a Reply

Your email address will not be published. Required fields are marked *