How to find the root Page of a specific Control in Xamarin.Forms

Actually it’s very easy to achieve this. Just traverse the visual tree upwards to find the root.

 public static class VisualTreeHelper
    {
        public static ContentPage FindParentPage(Element view)
        {
            if (view is ContentPage page)
            {
                return page;
            }
            return FindParentPage(view.Parent);
        }
    }

This does what we intended to do, but… we can do better than that!
Maybe we don’t want to just find the (Content)Page, how about finding the root grid, or a parent of a specific type. We just need to take that function and convert it to a generic function, that’s all, and we are way more flexible.

public static class VisualTreeHelper
    {
        public static T FindParentPage<T>(Element view)
            where T:Page
        {
            return FindParentElement<T>(view);
        }

        public static T FindParentElement<T>(Element view)
            where T:Element
        {
           
            if (view is T page)
            {
                return page;
            }
            if (view.Parent == null)
            {
                return null;
            }
            return FindParentElement<T>(view.Parent);
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.