Xamarin Forms Navigation Awareness

Xamarin Forms offers a NavigationPage control which allows you to do linear navigation and integrates with the native Back button on Android and Windows. However from the individual Page it isn’t possible to tell how you arrived at the page. I had a situation in a project where I needed to know whether a page appeared via a forward or backward navigation. The Page control doesn’t have an equivalent to the OnNavigatedTo / OnNavigatedFrom methods that Windows has.

I therefore came up with an implementation by writing a custom NavigationPage and adding an interface which a Page could optionally implement to expose the OnNavigatedTo / OnNavigatedFrom methods.

To add the functionality you merely need to replace the code (probably in App.cs) which initializes your NavigationPage to e.g.

MainPage = new InTheHand.Forms.NavigationPage2(new FirstPage());

Then in the page you add the interface:-

public partial class FirstPage : ContentPage, IPageNavigation

An add an implementation of these methods. Visual Studio can generate these for you but remember by default these will throw NotImplementedExceptions

public void OnNavigatedTo(InTheHand.Forms.NavigationEventArgs args)
   switch (args.NavigationMode)
      case NavigationMode.New:
         StatusLabel.Text = "Navigated forward to this page from " + (args.Page == null ? "<unknownpage>" : args.Page.GetType().ToString());

      case NavigationMode.Back:
         StatusLabel.Text = "Navigated backward to this page from " + (args.Page == null ? "<unknownpage>" : args.Page.GetType().ToString());

The sample project on GitHub demonstrates a simple scenario with three pages and multiple ways of navigating between them. Each shows a status label showing how the user navigated to the page. Because it hooks into the NavigationPage it isn’t linked to any controls you set up to programmatically navigate, nor does it matter if a back navigation was initiated by a hardware back button, or a programmatic navigation.


One thought on “Xamarin Forms Navigation Awareness

Comments are closed.