OnBackButtonPressed Not Firing Xamarin Forms

Viewed 7638

I am trying to prevent the user of my app from pressing the hardware back button. I have found this code snippet that is in the code behind the xaml file:

protected override bool OnBackButtonPressed()
    {
        return true;
    }

I have tried variations of this including using Boolean instead of Bool and returning base.functionname nothing seems to fire this method. Here is the bigger context:

Code behind:

namespace Watson.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class StartScan : ContentPage
    {
        public StartScan()
        {
            InitializeComponent();
        }
        protected override bool OnBackButtonPressed()
        {
            return true;
        }
    }
}

This is the second page in the stack and disabling the button only needs to happen on this page only, no where else.

Any help would be appreciated.

5 Answers

You can also add NavigationPage.SetHasBackButton property in the XAML

     NavigationPage.HasBackButton="True"

In the Content Page

You can do this way:

namespace Watson.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class StartScan : ContentPage
    {
        public StartScan()
        {
            NavigationPage.SetHasBackButton(this, false);
            InitializeComponent();
        }
        protected override bool OnBackButtonPressed()
        {
            // you can put some actions here (for example, an dialog prompt, ...)
            return true;
        }
    }
}

For me it is working with the following code (Samsung Android)

protected override bool OnBackButtonPressed()
{
    //base.OnBackButtonPressed();
    browser.GoBack();
    return true;
}

OnBackButtonPressed firing when you click the back button on your device, not from your navigation page, do your logic in OnDisappearing!

Related