Xamarin.Forms Navigation in Xamarin.Forms Hierarchical navigation with XAML


Example

By default, the navigation pattern works like a stack of pages, calling the newest pages over the previous pages. You will need to use the NavigationPage object for this.

Pushing new pages

...
public class App : Application 
{
    public App() 
    {
        MainPage = new NavigationPage(new Page1());
    }
}
...

Page1.xaml

...
<ContentPage.Content>
    <StackLayout>
        <Label Text="Page 1" />
        <Button Text="Go to page 2" Clicked="GoToNextPage" />
    </StackLayout>
</ContentPage.Content>
...

Page1.xaml.cs

...
public partial class Page1 : ContentPage
{
    public Page1()
    {
        InitializeComponent();
    }
    
    protected async void GoToNextPage(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new Page2());
    }
}
...

Page2.xaml

...
<ContentPage.Content>
    <StackLayout>
        <Label Text="Page 2" />
        <Button Text="Go to Page 3" Clicked="GoToNextPage" />
    </StackLayout>
</ContentPage.Content>
...

Page2.xaml.cs

...
public partial class Page2 : ContentPage
{
    public Page2()
    {
        InitializeComponent();
    }
    
    protected async void GoToNextPage(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new Page3());
    }
}
...

Popping pages

Normally the user uses the back button to return pages, but sometimes you need to control this programatically, so you need to call the method NavigationPage.PopAsync() to return to the previous page or NavigationPage.PopToRootAsync() to return at the beggining, such like...

Page3.xaml

...
<ContentPage.Content>
    <StackLayout>
        <Label Text="Page 3" />
        <Button Text="Go to previous page" Clicked="GoToPreviousPage" />
        <Button Text="Go to beginning" Clicked="GoToStartPage" />
    </StackLayout>
</ContentPage.Content>
...

Page3.xaml.cs

...
public partial class Page3 : ContentPage
{
    public Page3()
    {
        InitializeComponent();
    }
    
    protected async void GoToPreviousPage(object sender, EventArgs e)
    {
        await Navigation.PopAsync();
    }

    protected async void GoToStartPage(object sender, EventArgs e)
    {
        await Navigation.PopToRootAsync();
    }
}
...