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?
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.
I tried also to override Xamarin.Forms.NavigationPageOnBackButtonPressed()
but it doesn't work. Why?
Any one have already solved that issue?
I also tried by overriding OnDisappear()
, there are two problems:
- The page has already visually disappeared so the "Are you sure?" dialog appears over the previous page.
- Cannot cancel the back action.
So, is it possible to intercept the navigation bar back button press?
I was able to show a confirmation dialog that could cancel navigation by overriding the following methods in the FormsApplicationActivity.
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.
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:
In Xamarin.Forms, the Page class has an
OnBackButtonPressed()
method that you can tap into for all platformsThis is an inherently difficult task and the only way I got around it was to remove the back button entirely and then handle the backwards navigation from a 'save' button.
I have done a brief search of the Xamarin.Forms forum and the following has been suggested:
The link for the post is as follows:
https://forums.xamarin.com/discussion/21631/is-there-nay-way-of-cancelling-the-back-button-event-from-the-navigationpage
The easiest, as @JordanMazurke also somewhat mentions, since the event for the back button cannot be handled currently (other than the physical back button for Android), is to either:
NavigationPage.ShowHasBackButton(this, false)
Modal
instead of aPage
Then afterwards, you can add an
ActionbarItem
from where you can handle theEvent
.I personally spoke to the iOS team from Xamarin concerning this matter, and they basically told me we shouldn't expect support for handling the
Event
for theBackButtonPressed
in theNavigationBar
. The reason being, that on iOS, it's bad practice for the users to receive a message whenBack
is pressed.