Ever wanted to hook into a global navigation event for Xamarin.Forms? We’ve all seen the OnAppearing and OnDisappearing events in Xamarin, but did you know that there is a global event to know when a page has been loaded? Unfortunately for me, I’ve needed this event for a long time and never found it, despite it being listed in the Xamarin documentation :(

In one of the projects that I’ve worked on, I wanted to be able to track each page navigation event and send that data to Visual Studio App Center. This, unfortunately, involved a lot of code being copy and pasted to the OnAppearing event on every page, and then every time we need to add a new page to the app, we have to remember to include this code.

This got me looking for something better, something more global.

In your app.xaml.cs, you can add the following code that will capture an event for every OnAppearing event that is fired within your app, allowing us to do what we had to do on every page, once.

Application.Current.PageAppearing += OnPageAppearing

All you need to do now is create a method that the EventHandler can call, and we’ve achieved our aims.

private void OnPageAppearing(object sender, Page e)
{

}

That’s all it takes, however if you want something that is more usable to your application, for example if you wanted to use this event to send every page that is visited to App Center. The first thing you want to doi, is filter the type of page that you’re interested in (i.e. I’m only interested in the ContentPage). This will filter out the navigation pages and the flurry of events when you first open the app, as well as helping when using a master detail app.

private void OnPageAppearing(object sender, Page e)
{
    if (e is ContentPage)
    {
        Console.WriteLine($"Navigated to {e.GetType()}");
        // Add your code to push to app center here
    }
}

You can see a default Xamarin.Forms app here