Xamarin.Forms, a popular choice for cross-platform Xamarin apps, has two stacks. It’s common to implement navigation by pushing and popping Pages on a stack, but the two stacks are intended for very different situations and using the right one will make your code easier to understand. How do you know which stack you should use for your projects?
Today, we’re announcing a new class in the Xamarin University course schedule for Xamarin Certification! Navigation Patterns in Xamarin.Forms (XAM205) will show you how to code the stack and tab navigation patterns, including guidelines to help you decide which pattern is most appropriate for your app.
The Two Stacks
The two Xamarin.Forms stacks are the Navigation Stack and the Modal Stack. Each provides their own set of push/pop methods, as seen below:
Since the methods operate on different stacks, you must use them as pairs. For example, if you call
PushModalAsync to display a page, you must use
PopModalAsync to remove it, or you’ll get a runtime exception.
The Navigation Stack is implemented by the
NavigationPage class. This means it’s only available from pages hosted inside a
NavigationPage. The methods will throw an exception if you call
PopAsync without a
The Modal Stack, by contrast, with its
PopModalAsync methods, is always available from any page.
Every Page in Xamarin.Forms has a Navigation property of type
INavigation interface contains methods for both stacks:
public interface INavigation
Task PushAsync(Page page);
Task PushModalAsync(Page page);
The methods with Modal in their name operate on the Modal Stack. The non-modal methods work on the Navigation Stack.
What is a Modal Page?
A modal page is a page with restricted navigation options. The user must indicate that they are finished before moving to a different page.
The classic examples are pages like Add-New or Edit, where the user must choose whether to save their data before they leave the page. For example, the iOS Clock app uses tabs as its top-level navigation paradigm, shown below:
Notice how the tabs are hidden, so the user is forced to tap Cancel or Save to leave the page? This is the behavior we mean when we say a page is modal.
With that background, the guidance is straightforward:
PopAsyncwhen you’re implementing stack navigation using a NavigationPage.
PopModalAsynconly to display a modal page. This will make your code self-documenting; other developers will know immediately that you are implementing the concept of a modal page.
This is just a sample of the material in the Xamarin University course Navigation Patterns in Xamarin.Forms (XAM205), which shows you how to code the stack and tab navigation patterns, including guidelines to help you decide which pattern is appropriate for your app.