Find the Parent Control of a Specific Type in WPF and Silverlight

Brian Lagunas / Wednesday, May 29, 2013

I know this is no ground breaking, mind blowing secret trick, but I have been getting a surprising number of questions regarding how to find the parent of a specific type for a control.  The ability to find a parent control based on a type comes in real handy when dynamically composing views such as in a Prism application.  There are tons of other scenarios where this is useful, but the most recent request for this was based off my XamDockManager Prism Region Adapter post.  Someone wanted to create a behavior that would be attached to their view, which is injected into a ContentPane, to control whether the ContentPane could be closed or not.  Well since the cancellable Closing event exists on the ContentPane control itself and not on the View that was being injected, they needed access to the parent of type ContentPane from within the behavior.  Well, lucky for them this is really easy to do.

public static T FindParent<T>(DependencyObject child) where T : DependencyObject
{
    //get parent item
    DependencyObject parentObject = VisualTreeHelper.GetParent(child);

    //we've reached the end of the tree
    if (parentObject == null) return null;

    //check if the parent matches the type we're looking for
    T parent = parentObject as T;
    if (parent != null)
        return parent;
    else
        return FindParent<T>(parentObject);
}

 

This simple code snippet will traverse up the visual tree of the control looking for a parent control matching the specific type provided.  To use it, simple call the FindParent<T> method, where T is the type you are looking for, and then passing in the control in which you want to the parent of.

ContentPane _parentContentPane = FindParent<ContentPane>(this);
if (_parentContentPane != null)
    _parentContentPane.Closing += _parentContentPane_Closing;

 

This particular example searches up the visual tree of a user control looking for the xamDockManager ContentPane that contains the user control instance.  Oh, and did I mention that this exact code snippet will work the same in both WPF and Silverlight?  That was easy!

Feel free contact me on my blog, connect with me on Twitter (@brianlagunas), or leave a comment below for any questions or comments you may have.