Reputation: 27643
Is there a way to tell if a ContentPage is currently shown?
I need code inside an event handler in the ContentPage to check whether the page is currently shown and act accordingly.
Upvotes: 2
Views: 3611
Reputation: 5452
If you use Shell
as your MainPage
, you can run
bool isOnMyPage = Shell.Current.CurrentPage == MyPage
Upvotes: 0
Reputation: 4153
You can listen to the NavigationPage
's Pushed
and Popped
events, like so:
((Xamarin.Forms.NavigationPage)MyProject.App.Current.MainPage).Pushed += (s, e) =>
{
if (e.Page is ContentPage)
{
// Do what you gotta do
}
// or, for a specific page:
if (e.Page is MyProject.Views.MyCustomPage)
{
// Do what you gotta do
}
};
Of course, this will only be called when the page is pushed onto the navigation stack; If you need it to be called each time the page appears on the screen, then go with what GBreen12 or hvaughan3 said.
Upvotes: 2
Reputation: 11105
In addition to GBreen12's answer, you could also do it this way...
bool isShowingMyPage = Application.Current.MainPage is MyPage || (Application.Current.MainPage is NavigationPage navPage && navPage.CurrentPage is MyPage); //If you are using a MasterDetailPage or something else, then you would have to handle this differently
//I think the below will work for checking if any modals are showing over your page but you should definitely test it in different scenarios to make sure. I am not sure if the modal is immediately removed from ModalStack when it gets popped or not
isShowingMyPage = Application.Current.MainPage?.Navigation?.ModalStack?.LastOrDefault() == null;
Upvotes: 5
Reputation: 1900
You can override OnAppearing
which is called anytime the page is about to be shown:
Page lifecycle events in xamarin.forms
Upvotes: 2