Code Snippet: A recursive WPF Visual Tree child search

For when you want to find a child of a given type anywhere below a root element in the visual tree. I always end up writing these, so though I might as well post it for reference / review. Another candidate for a shared library.

private static DependencyObject RecursiveVisualChildFinder<T>(DependencyObject rootObject)
    var child = VisualTreeHelper.GetChild(rootObject, 0);
    if (child == null) return null;

    return child.GetType() == typeof (T) ? child : RecursiveVisualChildFinder<T>(child);

Share this: