xamarin - 检测 Xamarin 表单中 NavigationPage 的后退箭头按下
问题描述
有没有办法检测在 Xamarin 表单中按下导航页面的后退按钮?
解决方案
您可以覆盖导航页面的“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;
}
如果您使用的是外壳程序,您可以覆盖外壳程序的 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");
}
您可以在任何页面上覆盖这两种方法以跟踪它们何时出现和消失。
推荐阅读
- sas - sas 使文件夹名称中带有助记符的目录
- github - GitHub Repo 的 Google Cloud Builds 触发器始终显示“没有标签匹配”
- javascript - Asp:Calendar 总是返回默认日期,而不是单击按钮后用户选择的日期
- python - 我在编写一个正方形的函数时遇到了 Python 的问题
- r - 基于键列合并两个数据框的最佳方法
- python - 我如何在熊猫中解决这个问题?
- c - 2D 动态分配的数组可以访问比分配大小更多的内存
- c# - 如何直接从 DLL 访问 SQLite 数据库(不使用 app.config)?
- javascript - 当我连续两次执行一个简单的JS函数时,是否会花费两倍的计算能力?
- regex - 奇数个 a 和奇数个 b 的正则表达式