6
votes

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
Is this on a specific platform? Or any?Gerald Versluis
At the moment its being deployed on Android but it maybe extended to windows phones.user3355961
can you try setting this <ContentPage ....NameSpaces etc.... NavigationPage.HasBackButton="False" Title="MyPage"> </ContentPage>Naveen Bathina
I will try this, but im sure that is for the software button only. That needs to be disabled as well so I will put this in. But I dont think its for the hardware button.user3355961
For the record, that did nothing. It didnt affect the software or the hardware button.user3355961

5 Answers

3
votes

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,

2
votes

You can also add NavigationPage.SetHasBackButton property in the XAML

     NavigationPage.HasBackButton="True"

In the Content Page

1
votes

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;
        }
    }
}
1
votes

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

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

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