2

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.

ispiro
  • 26,556
  • 38
  • 136
  • 291
  • Register event handlers OnAppearing and remove on Disappearing then you don't have to worry about it. If you are using event handlers for IPC you are going to have a bad time and might want to refactor things a bit. – snowCrabs Feb 05 '18 at 21:18

3 Answers3

5

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;
hvaughan3
  • 10,955
  • 5
  • 56
  • 76
  • What if this page has been "pushed" or "pushed modal" over the `MainPage`? – ispiro Feb 05 '18 at 19:30
  • @ispiro If a new page was "pushed" over `MyPage` then `Application.Current.MainPage` would hold the new page and not `MyPage`. If you also need to worry about whether a modal is showing over your `MyPage`, then check out my edit. – hvaughan3 Feb 05 '18 at 19:36
  • Checking for modals worked – jcubero Sep 26 '22 at 21:52
2

You can override OnAppearing which is called anytime the page is about to be shown:

Page lifecycle events in xamarin.forms

GBreen12
  • 1,832
  • 2
  • 20
  • 38
1

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.

sme
  • 4,023
  • 3
  • 28
  • 42