【发布时间】:2019-08-26 17:38:28
【问题描述】:
有没有什么方法可以检测 Xamarin 表单中导航页面的后退按钮的按下?
【问题讨论】:
-
请在POST查看我的回答
标签: xamarin xamarin.forms navigation
有没有什么方法可以检测 Xamarin 表单中导航页面的后退按钮的按下?
【问题讨论】:
标签: xamarin xamarin.forms navigation
您可以覆盖导航页面的“OnBackButtonPressed”方法:
protected override bool OnBackButtonPressed()
{
Device.BeginInvokeOnMainThread(async () =>
{
if (await DisplayAlert("Exit?", "Are you sure you want to exit from this page?", "Yes", "No"))
{
base.OnBackButtonPressed();
await App.Navigation.PopAsync();
}
});
return true;
}
如果你使用的是shell,你可以覆盖Shell的OnNavigating事件:
void OnNavigating(object sender, ShellNavigatingEventArgs e)
{
// Cancel back navigation if data is unsaved
if (e.Source == ShellNavigationSource.Pop && !dataSaved)
{
e.Cancel();
}
}
更新: OnBackButtonPressed 事件只会在用户按下硬件后退按钮时在 Android 上触发。
当任何页面消失时,您似乎更有兴趣实施您想做的事情! 在这种情况下: 你有页面的两种方法 -
protected override void OnAppearing()
{
base.OnAppearing();
Console.WriteLine("Hey, Im coming to your screen");
}
protected override void OnDisappearing()
{
base.OnDisappearing();
Console.WriteLine("Hey, Im going from your screen");
}
您可以在任何页面上覆盖这两种方法以跟踪它们何时出现和消失。
【讨论】:
您必须使用自定义渲染器覆盖本机导航栏按钮行为。 OnBackButtonPressed 仅触发物理设备按钮。你可以阅读好文章如何实现这个here
【讨论】:
最近对 Xamarin 表单的更新意味着您现在可以在使用 Shell Navigation 制作的应用程序中执行此操作,以便在两个平台上进行导航返回箭头。
使用 Shell.SetBackButtonBehavior 方法,例如在页面对象的构造函数中运行此代码将允许仅在绑定的视图模型不忙时进行后退导航:
Shell.SetBackButtonBehavior(this, new BackButtonBehavior
{
Command = new Command(async() =>
{
if (ViewModel.IsNotBusy)
{
await Shell.Current.Navigation.PopAsync();
}
})
});
在命令的正文中,您可以在拦截后退按钮的单击时做任何您需要做的事情。
【讨论】: