Finding the Parent

I didn’t realise that getting to the parent FrameworkElement was so easy. This code came from the Silverlight.net Forum, I like to link but I’ve lost the post.

GetParent((FrameworkElement)this, typeof(Grid));
private FrameworkElement GetParent(FrameworkElement child, Type targetType)
        {
            object parent = child.Parent;
            if (parent != null)
            {
                if (parent.GetType() == targetType)
                {
                    return (FrameworkElement)parent;
                }
                else
                {
                    return GetParent((FrameworkElement)parent, targetType);
                }
            }
            return null;
        }

A better way to find the parent using the VisualTreeHelper found on the Silverlight forums:

public static class ControlFinder
    {
        public static T FindParent<T>(UIElement control) where T: UIElement
        {
            UIElement p = VisualTreeHelper.GetParent(control) as UIElement;
            if (p != null)
            {
                if (p is T)
                    return p as T;
                else
                    return ControlFinder.FindParent<T>(p);
            }
            return null;
        }
}

Page p = ControlFinder.FindParent<Page>(CurrentControl);

if(p != null)

{

      // here is your Page Control that in the parent chain 

}
Advertisements
  1. No trackbacks yet.

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

%d bloggers like this: