Navigating in Xamarin Forms

Switching pages in Xamarin Forms is simple, once you understand the core concepts of setting the MainPage or using a page with navigational abilities.

Navigating mobile phone

Main Page

In App.cs or App.xaml.cs you will have an assignment to your MainPage.

MainPage = new ContentPage() { Content = new Label() { Text= "Hello World"  } };

A TabbedPage, ContentPage, NavigationPage can be assigned to the Main Page, which is statically available throughout your app.

Application.Current.MainPage

This comes at the disadvantage of not providing any navigational history using MainPage switching. Pressing the back button will result in the app backgrounding.

NavigationPage

To keep navigational history and provide mechanisms to move back and forward through pages in your app you need a NavigationPage. For keeping a list of page the NavigationPage has two stacks, the ModalStack and NavigationStack.

NavigationPage.Navigation.ModalStack
NavigationPage.Navigation.NavigationStack

You can assign a NavigationPage to MainPage as below. You must add a first page before the constructor finishes when assigning the MainPage in the App constructor.

MainPage = new NavigationPage(new MyFirstPage());

NavigationStack

Your main navigational stack is the NavigationStack, which you can Push and Pop from. Pushing adds a page to the stack, pop removes it. It is a simple queue of Last In, First Out.

var navPage = new NavigationPage(new MyFirstPage());
Application.Current.MainPage = navPage;

await navPage.PushAsync(new MySecondPage());

Popping the stack is similar. Receiving a Popped Notification is also possible.

await navPage.PopAsync();

// To monitor Pop's
navPage.Popped += (s, e) => { };

ModalStack

The ModalStack is equivalent of putting another page with a different stack on top of your other stack. Think of it as a Pop Over page with its own navigation.

navPage.Navigation.PushModalAsync(new MyFirstModalPage());
navPage.Navigation.PopModalAsync();

ViewModel Navigation

Manipulating the NavigationPage and MainPage is the main way in which Xamarin Forms provides navigation to your app. However, Xamarin Forms is designed with MVVM in mind. You must perform navigation in the ViewModel if you want to adhere to the MVVM pattern. Fortunately there are many MVVM Helper libraries which do just that.

Microsoft MVP | Xamarin Certified Developer |
Exrin Creator | Xamarin Forms Developer | Melbourne, Australia

Related Posts

Leave A Comment?