VisualTreeHelper for Xamarin.Forms

Here’s my implementation for GetParent and GetChildren:

?

public static class VisualTreeHelper

{

    public static T GetParent(this Element element) where T : Element

    {

        if (element is T)

        {

            return element as T;

        }

        else

        {

            if (element.Parent != null)

            {

                return element.Parent.GetParent();

            }

 

            return default(T);

        }

    }

         

    public static IEnumerable GetChildren(this Element element) where T : Element

    {

        var properties = element.GetType().GetRuntimeProperties();

 

        // try to parse the Content property

        var contentProperty = properties.FirstOrDefault(w => w.Name == "Content");

        if (contentProperty != null)

        {

            var content = contentProperty.GetValue(element) as Element;

            if (content != null)

            {

                if (content is T)

                {

                    yield return content as T;

                }

                foreach (var child in content.GetChildren())

                {

                    yield return child;

                }

            }

        }

        else

        {

            // try to parse the Children property

            var childrenProperty = properties.FirstOrDefault(w => w.Name == "Children");

            if (childrenProperty != null)

            {

                // loop through children

                IEnumerable children = childrenProperty.GetValue(element) as IEnumerable;

                foreach (var child in children)

                {

                    var childVisualElement = child as Element;

                    if (childVisualElement != null)

                    {

                        // return match

                        if (childVisualElement is T)

                        {

                            yield return childVisualElement as T;

                        }

 

                        // return recursive results of children

                        foreach (var childVisual in childVisualElement.GetChildren())

                        {

                            yield return childVisual;

                        }

                    }

                }

            }

        }

    }

}

As the VisualTreeHelper is implemented as a static class, it can be used stand-alone or as extension methods on an object:

?

// from within user control...

 

Page page = null;

StackLayout stack = this.FindByName("myStack");

 

// utility class

page = VisualTreeHelper.GetParent(stack);

 

// using extension method

page = stack.GetParent();

Well, that's it for now. My next post will show how a practical example.

Happy coding.

你可能感兴趣的:(xamarin)