Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper Page.Loaded event in Xamarin.Forms

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.

like image 870
Abdelfattah Radwan Avatar asked Oct 25 '25 05:10

Abdelfattah Radwan


1 Answers

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();
        }
    }
}
like image 61
nevermore Avatar answered Oct 27 '25 00:10

nevermore