Posts Tagged visual parent

Finding a typed visual parent in Silverlight


My application frequently needs to find a parent of a Silverlight element, and due to the nature of popup panels I also sometimes want to know if the element is “logically” connected to another element.  To achieve this I wrote a couple of helper functions that walk the visual tree and return a typed parent.  You can implement a special interface to indicate that there is a logical connection between items that aren’t physically connected to each other in the Visual Tree too if you need to (very helpful with focus issues).


        public static T FirstVisualAncestorOfType<T>(this DependencyObject element) where T : DependencyObject
        {
            if (element == null) return null;
           
            var parent = VisualTreeHelper.GetParent(element) as DependencyObject;
            while (parent != null)
            {
                if (parent is T)
                    return (T)parent;
                if (parent is IBreakVisualParenting)
                {
                    parent = ((IBreakVisualParenting)parent).Parent;
                }
                else
                    parent = VisualTreeHelper.GetParent(parent) as DependencyObject;
            }
            return null;
        }

        public interface IBreakVisualParenting
        {
            DependencyObject Parent { get; }
        }

        public static T LastVisualAncestorOfType<T>(this DependencyObject element) where T : DependencyObject
        {
            T item = null;
            var parent = VisualTreeHelper.GetParent(element) as DependencyObject;
            while (parent != null)
            {
                if (parent is T)
                    item = (T) parent;
                if(parent is IBreakVisualParenting)
                {
                    parent = ((IBreakVisualParenting) parent).Parent;
                }
                else
                    parent = VisualTreeHelper.GetParent(parent) as DependencyObject;
            }
            return item;
        }

, ,

Leave a comment