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.
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.
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;
You can override OnAppearing
which is called anytime the page is about to be shown:
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.