使用 XAML 进行分层导航

默认情况下,导航模式就像一堆页面一样工作,调用前一页面上的最新页面。你需要使用 NavigationPage 对象。

推送新页面

...
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());
    }
}
...

弹出页面

通常用户使用后退按钮返回页面,但有时你需要以编程方式控制它,因此你需要调用方法 NavigationPage.PopAsync() 返回上一页或 NavigationPage.PopToRootAsync() 以在开始时返回,像……

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();
    }
}
...