Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 77050

Element.ParentPage() Extension

$
0
0

Here's is a little extension that I wrote to find the parent Page for a given element. I use it for custom Views and in custom renderers. Thought it would be helpful for others, as it took me a little while to figure out how to get it to work well.

public static class FormsEntension
{
    /// <summary>
    /// Returns the Page which is the closest ancestor to this element.
    /// </summary>
    /// <returns>The parent Page.</returns>
    /// <param name="element">Element.</param>
    public static Page ParentPage (this Element element)
    {
        var parent = element.ParentView;
        var page = parent as Page;

        return page ?? parent.ParentPage ();
    }
}

Example usage :

public partial class ChatMessageView : ContentView
{
    string error;

    public ChatMessageView ()
    {
        Init();

        if (error != null)      
            this.ParentPage ().DisplayAlert ("Error", error, "OK");
    }

    void Init()
    {
        InitializeComponent ();
        //Do stuff...
    }
}

Viewing all articles
Browse latest Browse all 77050

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>