Sunday, May 01, 2011

Get a visual parent of an element in Silverlight

Remember that you don’t have a parent in your control’s constructor -- it hasn’t been added anywhere yet.  Use the Loaded event when you look.  From there, you can use the VisualTreeHelper.GetParent() method.  Sometimes you are looking for a parent of a given name or type.  To help out, here’s a quick method I threw together to help you find a parent of a given type:
T GetParentOfType<T>() where T : DependencyObject
{
    DependencyObject p = this;
    
    while( p != null && !(p is T))
    {
        p = VisualTreeHelper.GetParent(p);
    }

Read more: Arian Kulp's Site