Monday, June 27, 2011

VisualTreeHelper - Your New Best Friend

Ever noticed that WPF and Silverlight don't like to play nicely with their implementations of the same controls?  Often, this is because they are derived differently.  They both ultimately derive from DependencyObject, however the

In any case, the VisualTreeHelper is your best friend when it comes to navigating the structure of your controls.  Essentially, it allows you to navigate down from a parent element, locating children.  You can be a little recursive and then use the VisualTreeHelper on the child controls and dig deeper and deeper.

I've written a little helper that I've injected into the base class of all controls I'm writing for Silverlight and WPF.

/// <summary>
/// Navigates the control tree to find a child of a specific type.
/// </summary>
/// <param name="element">The parent element to search under.</param>
/// <param name="type">The type to search for.</param>
/// <returns>The first child of the specified type on success or null on failure.</returns>
protected object GetChildOfType(FrameworkElement element, Type type)
    int count = VisualTreeHelper.GetChildrenCount(element);
    for (int i = 0; i < count; i++)
        FrameworkElement child = (FrameworkElement)VisualTreeHelper.GetChild(element, i);
        if (child != null)
            if (child.GetType() == type)
                return child;
            object deeperChild = GetChildOfType(child, type);
            if (deeperChild != null)
                return deeperChild;
    return null;


No comments:

Post a Comment