首页 > 解决方案 > 检测 Xamarin 表单中 NavigationPage 的后退箭头按下

问题描述

有没有办法检测在 Xamarin 表单中按下导航页面的后退按钮?

标签: xamarinxamarin.formsnavigation

解决方案


您可以覆盖导航页面的“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");
    }

您可以在任何页面上覆盖这两种方法以跟踪它们何时出现和消失。


推荐阅读