Xamarin 跳转页面
准备三个 ContentPage 对象,暂时无需xaml:
MainPage.cs、ModelessPage.cs、ModalPage.cs。
MainPage.cs:
using System;
using Xamarin.Forms;
namespace one
{
public class MainPage : ContentPage
{
public MainPage()
{
Title = "Main Page";
Button gotoModelessButton = new Button {
Text = "Go to modeless Page",
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.CenterAndExpand
};
gotoModelessButton.Clicked += async (sender, e) => {
await Navigation.PushAsync(new ModelessPage());
};
Button gotoModalButton = new Button {
Text = "Go to Modal Page",
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.CenterAndExpand
};
gotoModalButton.Clicked += async (sender, e) => {
await Navigation.PushModalAsync(new ModalPage());
};
Content = new StackLayout
{
Children = {
gotoModelessButton,
gotoModalButton
}
};
}
}
}
ModelessPage.cs:
using System;
using Xamarin.Forms;
namespace one
{
public class ModelessPage : ContentPage
{
public ModelessPage()
{
Title = "Modeless Page";
Button goBackButton = new Button {
Text = "Back to Main",
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
};
goBackButton.Clicked += async (sender, e) => {
await Navigation.PopAsync();
};
Content = goBackButton;
}
}
}
ModalPage.cs:
using System;
using Xamarin.Forms;
namespace one
{
public class ModalPage : ContentPage
{
public ModalPage()
{
Title = "Modal Page";
Button goBackButton = new Button
{
Text = "Back to Main",
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
};
goBackButton.Clicked += async (sender, e) => {
await Navigation.PopModalAsync();
};
Content = goBackButton;
}
}
}
加载内容:
using Xamarin.Forms;
namespace one
{
public partial class App : Application
{
public App()
{
MainPage = new NavigationPage(new MainPage());
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
运行~~:
点击"Go to modeless Page":
点击 "Back to Main" 即可返回到首页,与 顶部左边的 Back 按钮同等功能。
点击"Go to Modal Page":
点击 "Back to Main" 即可返回到首页。
总结一下:
Navigation.PushAsync() 类似 iOS 中 UINavigationController 的 pushViewController;
Navigation.PushModalAsync() 类似 iOS 中 presentViewController;