Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnBackButtonPressed Not Firing Xamarin Forms

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.

like image 919
user3355961 Avatar asked Jun 02 '17 10:06

user3355961


5 Answers

This is working for me, I tried in Android and iOS platforms using Xamarin.Forms.

Hope you can resolve with this piece of code.

namespace Test
{
    public partial class TestPage2 : ContentPage
    {
        public TestPage2()
        {
           NavigationPage.SetHasBackButton(this, false);
           InitializeComponent();
        }

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

Thanks,

like image 135
Naveen Bathina Avatar answered Nov 12 '22 12:11

Naveen Bathina


You can also add NavigationPage.SetHasBackButton property in the XAML

     NavigationPage.HasBackButton="True"

In the Content Page

like image 37
Noob Coder Avatar answered Nov 12 '22 14:11

Noob Coder


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;
        }
    }
}
like image 34
Tô Minh Tiến Avatar answered Nov 12 '22 14:11

Tô Minh Tiến


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

protected override bool OnBackButtonPressed()
{
    //base.OnBackButtonPressed();
    browser.GoBack();
    return true;
}
like image 33
Eelze Wijma Avatar answered Nov 12 '22 14:11

Eelze Wijma


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

like image 27
STG Avatar answered Nov 12 '22 12:11

STG