Xamarin.forms: How detect pressed software button NavigationBack?

Created on 17 Oct 2019  路  14Comments  路  Source: xamarin/Xamarin.Forms

No way how catch pressed software button NavigationBack.
image

question

All 14 comments

you can override OnAppearing, OnDisappearing in code behind

you can override OnAppearing, OnDisappearing in code behind

Override OnAppearing and OnDisappearing - can not break action NavigationBack, when user taped button (software) Back.

The question is still relevant.

@scriptBoris you need override OnBackButtonPressed() in your page.

protected override bool OnBackButtonPressed()
{
    //put your logic here
}

And you need to return true or false depending on whether you want to do the navigation back or not.

@KSemenenko this code is not executed

https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.navigationpage.onbackbuttonpressed?view=xamarin-forms

@VladislavAntonyuk you can try next code, and put break point.

protected override bool OnBackButtonPressed()
{
    return OnBackButtonPressed();
}

If you return true from then you will not go back to the previous page, unless you also call the base method in your override.

@Ksemenenko if you press back button of android the code is executed, but the question is about arrow. See screenshot

@VladislavAntonyuk @scriptBoris also if you check https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Platform.Android/AppCompat/FormsAppCompatActivity.cs then find that the code is already there and my code should work. But it is not. What version of Xamarin.Forms are you using?
Are you using NavigationPage or MasterDetailPage?

https://theconfuzedsourcecode.wordpress.com/2017/03/12/lets-override-navigation-bar-back-button-click-in-xamarin-forms/
@VladislavAntonyuk

image
Xamarin Forms 4.1
MasterPage, MasterDetail - NavigationPage ...

The problem is not solved. Help please!

Seems it's a bug, I will look for a solution to the problem

There is no simple way to do this. As pointed out upthread, there are some hacks and tricks you can employ to do this (see: https://xamarinhelp.com/xamarin-forms-back-navigation-pitfalls/).

If this is a feature you would like, I suggest opening a feature request.

@scriptBoris Another option would be to move your application to use Xamarin.Forms Shell - Shell has a Navigating event that you can intercept and cancel: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/shell/navigation#navigation-events

Was this page helpful?
0 / 5 - 0 ratings