Return to Snippet

Revision: 52910
at November 4, 2011 19:57 by tikluganguly


Initial Code
using System.Windows;
using System.Windows.Media;

namespace Utils
{
    /// <summary>
    /// The class contains the externsion helper methods
    /// for the visual tree
    /// </summary>
    public static class VisualTreeExtensions
    {
        /// <summary>
        /// This method will return the parent object of a specific type for a 
        /// particular element
        /// </summary>
        /// <typeparam name="T">the type of the parent we are looking for</typeparam>
        /// <param name="element">the element on which we are looking for the parent</param>
        /// <returns>if properly found then the parent object otherwise null</returns>
        public static T GetParent<T>(this DependencyObject element) where T : DependencyObject
        {
            var parent = VisualTreeHelper.GetParent(element);
            if (parent == null)
            {
                return null;
            }
            else if (parent is T)
            {
                return (T)parent;
            }
            else
            {
                return parent.GetParent<T>();
            }
        }

    }
}

Initial URL


Initial Description
Code to find the parent of a specific type for an object in silverlight

Initial Title
Visual Tree Parent Searcher

Initial Tags


Initial Language
C#