Posts Tagged Silverlight actually visible

IsInVisualTree – helper function for determining if a Silverlight item is visible or in the visual tree


Some Silverlight functions, especially those to do with coordinate transforms, tend to throw exceptions if the item you are testing isn’t in the visual tree and it is often interesting to know if an item is presently going to be displayed or not.  The following code uses the standard way of determining this, by walking the visual tree to see if the item is connected to the root visual of the application.  Being in the visual tree doesn’t mean the item is actually visible, this depends on the collapsed state of the element and its parents.


        /// <summary>
        /// Determines if an element is in the visual tree
        /// </summary>
        /// <param name="element">The element.</param>
        /// <returns>
        ///  <c>true</c> if element parameter is in
        ///  visual tree otherwise, <c>false</c>.
        /// </returns>
        public static bool IsInVisualTree(this DependencyObject element)
        {
            return IsInVisualTree(element, Application.Current.RootVisual as DependencyObject);
        }

        public static bool IsInVisualTree(this DependencyObject element, DependencyObject ancestor)
        {
            DependencyObject fe = element;
            while (fe != null)
            {
                if (fe == ancestor)
                {
                    return true;
                }

                fe = VisualTreeHelper.GetParent(fe) as DependencyObject;
            }

            return false;
        }

To test if an item is visible you just walk the parents and check the Visibility state:


        public static bool IsVisible(this FrameworkElement ele, FrameworkElement topParent=null)
        {
            if (!ele.IsInVisualTree()) return false;

            while(ele != topParent && ele != null)
            {
                if (ele.Visibility == Visibility.Collapsed) return false;
               ele = VisualTreeHelper.GetParent(ele) as FrameworkElement;
            }
            return true;
        }

, , , , ,

Leave a comment