Page lifecycle events in xamarin.forms

拜拜、爱过 提交于 2019-12-17 16:32:13

问题


I just developed my first xamarin.forms app. I am excited about xamarin.forms, but I miss several events.

Are there any page-lifecycle-events in a xamarin.forms ContentPage?

I know of these two:

protected override void OnAppearing()
{
}

protected override void OnDisappearing()
{
}

But the OnAppearing() event only fires once. On Android, when I push the start button and go back to my app, this event does not fire again.

Is there a workaround for this (like OnNavigatedTo in WindowsPhone-pages)?

Thanks.


回答1:


So the OnAppearing event is fired when your page is appearing. I.e. you have navigated to that page or back to that page from another in the Stack. There is currently no Page Lifecycle events as you can see from the API documentation

I think what you are talking about is if you put your application to sleep and navigate back into it the OnAppearing event is not fired, This is because your page hasn't appeared because it was already there, the application was just asleep.

What you are looking for is the App Lifecycle which includes methods such as:

protected override void OnStart()
{
    Debug.WriteLine ("OnStart");
}
protected override void OnSleep()
{
    Debug.WriteLine ("OnSleep");
}
protected override void OnResume()
{
    Debug.WriteLine ("OnResume");
}

You can then use the OnResume event to do what you are looking for.

That Xamarin Document includes the changes that must be made to old Xamarin projects to access these events. e.g. your App class in your shared library must inherit from Xamarin.Forms.Application and changes must also be made to the AppDelegate and MainActivity.




回答2:


You could also use Xamarin's MessagingCenter to perform arbitrary coordination of events: http://developer.xamarin.com/guides/cross-platform/xamarin-forms/messaging-center/

I've been frustrated by the same thing: not having consistent view life cycle events in Xamarin.Forms. But you can get around some of those constraints by using the MessagingCenter, which is just a simple pub/sub messaging facility.




回答3:


This is working for me. Xamarin.Forms 2.0 and above. Whenever you back to this CP page, the Appearing Event is fired.

    public CP:ContentPage
    {
        //....
        public CP()
        {
            this.Appearing += CP_Appearing ;
            //...
        }

        private void CP_Appearing(object sender, EventArgs e)
        {
            Debug.WriteLine("*************HALLO******WELCOME BACK.");
        }
    }


来源:https://stackoverflow.com/questions/29252351/page-lifecycle-events-in-xamarin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!