A generic function to find a visual child from a visual tree

Here’s a simple function you can use to get a specific child from a given visual tree. For example, you may want to get a handle to the scrollviewer in a listbox control. Here’s how you’d use the function to do that :-

ScrollViewer scrollViewer = FindChildControl<ScrollViewer>(searchResultsListbox);

And here’s the function listing :-

private T FindChildControl<T>(DependencyObject outerDepObj) where T:DependencyObject
{
    T child = null;

    for (int index = 0; index < VisualTreeHelper.GetChildrenCount(outerDepObj); index++)
    {
        DependencyObject depObj = VisualTreeHelper.GetChild(outerDepObj, index);

        if (depObj is T)
        {
            child = depObj as T;
        }
        else if (VisualTreeHelper.GetChildrenCount(depObj) > 0)
        {
            child = FindChildControl<T>(depObj);
        }

        if (child != null)
        {
            break;
        }
    }

    return child;
}
Advertisements

2 thoughts on “A generic function to find a visual child from a visual tree

  1. There is a double cast to T in the code. IMO code it can be reduced to, that only one cast (operator “as”) will be performed.

    if ((child = depObj as T) != null)
    {
    break;
    }
    else if (VisualTreeHelper.GetChildrenCount(depObj) > 0)
    {
    child = FindChildControl(depObj);
    }

  2. I figured out our code to make it find a parent object.

    public static T FindParentControl(DependencyObject innerDepObj) where T : DependencyObject
    {
    T parent = null;

    while (innerDepObj != null)
    {
    innerDepObj = VisualTreeHelper.GetParent(innerDepObj);

    if (innerDepObj is T)
    {
    parent = innerDepObj as T;
    break;
    }
    }

    return parent;
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s