Wednesday, April 28, 2010

How to find the visual parent or child element using VisualTreeHelper

VisualTreeHelper is very useful class which help us to find or drill-down element from the hosted container.

The following method will help you to find the visual parent element from the container.

    public static T FindVisualParent<T>(UIElement element) where T : UIElement
    {
        UIElement parent = element;
        while (parent != null)
        {
            T correctlyTyped = parent as T;
            if (correctlyTyped != null)
            {
                return correctlyTyped;
            }
            parent = VisualTreeHelper.GetParent(parent) as UIElement;
        }
        return null;
    }

The following method will help you to find the child element from the container.

    public static T FindChild<T>(DependencyObject parent)where T : DependencyObject
    {
        if (parent == null) return null;

        T childElement = null;
        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            T childType = child as T;
            if (childType == null)
            {
                childElement = FindChild<T>(child);
                if (childElement != null) break;
            }
            else
            {
                childElement = (T)child;
                break;
            }
        }
        return childElement;
    }
Post a Comment