Proper Page.Loaded event in Xamarin.Forms

Viewed 5629

For the past 2 month I have been searching tirelessly for a way to implement a proper Page.Loaded event when using Xamarin.Forms but I couldn't implement or find a way to do it.

Most people suggest overriding Page.OnAppearing or adding an event handler for Page.Appearing both of which are not the answers or the proper way to achieve the desired effect and don't event behave as a real Page.Loaded event would.

I would like to know the following:

  • Why doesn't Xamarin.Forms have a built-in Page.Loaded event?
  • Is there's a work around?
  • Can I implement it from the native side?

Edit:

What I mean by "proper Page.Loaded" event is:

  • It must be called ONCE AND ONLY ONCE the page has loaded all of it's controls, laid them out, initialized them and rendered them for the first time.

  • It must NOT be called when returning from modal pages.

2 Answers

Currently Xamarin.Forms doesn't not provide a proper/complete life cycle events to fulfill all specific requirements, but things are improving, the Dev team is currently working on to address this issue, below mentioned issues and recent pull request on the official GitHub Repos (you may follow, get ideas and maybe implement it yourself before they even ship it), they will for sure provide that in the future, although it is not clear when it will be ready.

1.Why not load the data/controls in the constructor of the ContentPage? The constructor method is call only once and it is also called before Page.OnAppearing.

Can I implement it from the native side?

Yes, I think you can.

In iOS, override the ViewDidLoad method in custom renderer:

[assembly:ExportRenderer (typeof(ContentPage), typeof(MyPageRenderer))]
namespace App487.iOS
{
    public class MyPageRenderer : PageRenderer
    {

        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            //call before ViewWillAppear and only called once
        }

        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);
        }
    }
}

In Android, try to override the OnAttachedToWindow method:

[assembly: ExportRenderer(typeof(ContentPage), typeof(MyPageRenderer))]
namespace App487.Droid
{
    public class MyPageRenderer : PageRenderer
    {
        public MyPageRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
            base.OnElementChanged(e);
        }

        protected override void OnAttachedToWindow()
        {
            base.OnAttachedToWindow();
        }
    }
}
Related