How to intercept Navigation Bar Back Button Clicked in Xamarin Forms?

前端 未结 6 1634
死守一世寂寞
死守一世寂寞 2020-12-07 00:41

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 bee

6条回答
  •  星月不相逢
    2020-12-07 01:32

    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();
         }
      }
    

    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];
    

提交回复
热议问题