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