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

前端 未结 6 1638
死守一世寂寞
死守一世寂寞 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:19

    As has already been said - you cannot do this cross-platform. However, you can handle it natively with arguably not so much effort: https://theconfuzedsourcecode.wordpress.com/2017/03/12/lets-override-navigation-bar-back-button-click-in-xamarin-forms/

    The article covers iOS and Android. If you have a UWP project you'll have to hammer your own solution for it.

    Edit: Here is the UWP solution! It actually turned out to be pretty easy – there is just one back button and it’s supported by Forms so you just have to override ContentPage’s OnBackButtonPressed:

        protected override bool OnBackButtonPressed()
        {
            if (Device.RuntimePlatform.Equals(Device.UWP))
            {
                OnClosePageRequested();
                return true;
            }
            else
            {
                base.OnBackButtonPressed();
                return false;
            }
        }
    
        async void OnClosePageRequested()
        {
            var tdvm = (TaskDetailsViewModel)BindingContext;
            if (tdvm.CanSaveTask())
            {
                var result = await DisplayAlert("Wait", "You have unsaved changes! Are you sure you want to go back?", "Discard changes", "Cancel");
    
                if (result)
                {
                    tdvm.DiscardChanges();
                    await Navigation.PopAsync(true);
                }
            }
            else
            {
                await Navigation.PopAsync(true);
            }           
        }
    

提交回复
热议问题