如何拦截在 Xamarin 表单中单击的导航栏后退按钮? [英] How to intercept Navigation Bar Back Button Clicked in Xamarin Forms?

查看:26
本文介绍了如何拦截在 Xamarin 表单中单击的导航栏后退按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 xamarin 表单页面,用户可以在其中更新表单中的一些数据.我需要拦截 Navigation Bar Back Button Clicked 以警告用户如果一些数据没有保存.怎么做?

I have a xamarin form page where a user can update some data in a form. I need to intercept the Navigation Bar Back Button Clicked to warn the user if some data have not been saved.How to do it?

我可以使用 Android.MainActivity.OnBackPressed() 在 Android 中拦截硬件 Bar Back Button Clicked,但该事件仅在硬件 Bar Back Button Clicked 上引发,而不是在 Navigation 上引发单击栏后退按钮.

I'm able to intercept the hardware Bar Back Button Clicked in Android using the Android.MainActivity.OnBackPressed(), but that event is raised only on hardware Bar Back Button Clicked, not on Navigation Bar Back Button Clicked.

我也尝试覆盖 Xamarin.Forms.NavigationPageOnBackButtonPressed() 但它不起作用.为什么?有人已经解决了这个问题吗?

I tried also to override Xamarin.Forms.NavigationPageOnBackButtonPressed() but it doesn't work. Why? Any one have already solved that issue?

我也试过重写OnDisappear(),有两个问题:

I also tried by overriding OnDisappear(), there are two problems:

  1. 该页面已经在视觉上消失了,所以你确定吗?"对话框出现在上一页上.
  2. 无法取消后退操作.

那么,是否可以拦截导航栏返回按钮按下?

So, is it possible to intercept the navigation bar back button press?

推荐答案

我能够显示一个确认对话框,该对话框可以通过覆盖 FormsApplicationActivity 中的以下方法来取消导航.

I was able to show a confirmation dialog that could cancel navigation by overriding the following methods in the FormsApplicationActivity.

  // navigation back button
  public override bool OnOptionsItemSelected(IMenuItem item)
  {
     if (item.ItemId == 16908332)
     {
        var currentViewModel = (IViewModel)navigator.CurrentPage.BindingContext;
        currentViewModel.CanNavigateFromAsync().ContinueWith(t =>
        {
           if (t.Result)
           {
              navigator.PopAsync();
           }
        }, TaskScheduler.FromCurrentSynchronizationContext());
        return false;
     }
     else
     {
        return base.OnOptionsItemSelected(item);
     }
  }

  // hardware back button
  public async override void OnBackPressed()
  {
     var currentViewModel = (IViewModel)navigator.CurrentPage.BindingContext;

     // could display a confirmation dialog (ex: "Cancel changes?")
     var canNavigate = await currentViewModel.CanNavigateFromAsync();
     if (canNavigate)
     {
        base.OnBackPressed();
     }
  }

navigator.CurrentPage 是 INavigation 服务的包装器.我不必从模态页面取消导航,所以我只处理 NavigationStack.

The navigator.CurrentPage is a wrapper around the INavigation service. I do not have to cancel navigation from modal pages so I am only handling the NavigationStack.

this.navigation.NavigationStack[this.navigation.NavigationStack.Count - 1];

这篇关于如何拦截在 Xamarin 表单中单击的导航栏后退按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆