.Net Maui Shell OnBackButtonPressed

114 views Asked by At

We have overridden the OnBackButtonPressed event for our shell application so the Android device back button will use custom code. We are only dealing with the Android device back button at this time. We have various scenarios where we want to go to specific pages based on where the page that sends the back button pressed command. This all appears to work fine.

The challenge I am having is, that in certain situations like being on the first page of the application, we want the standard back button behavior (i.e. exit the application) to take effect. To accomplish this, I tried putting the following code in the overridden OnBackButtonPressed event.

protected override bool OnBackButtonPressed()
{
   try
   {
       ---- various other conditions here ---

       if (currentPageType == typeof(CommissionPage))
       {
           var result = base.OnBackButtonPressed();
       }
   }
   catch (Exception ex)
   {
       ExceptionExtension.TrackError(ex);
       return false;
   }
   return true;
}

The intent was for this to trigger the default back button behavior. However, when I tap the back button on this page, it does execute the base.OnBackButtonPressed, but the application is not exited. The result of the call is returning false which I believe indicates the call was not handled as expected and I do not know why.

I am looking for a way from within my overridden OnBackButtonPressed code to for the default code to handle the back button.

Update

So I am going to post the correct code for ease of finding. I was not returning the result of my base.OnBackButtonPressed() call.

protected override bool OnBackButtonPressed()
{
   try
   {
       ---- various other conditions here ---

       if (currentPageType == typeof(CommissionPage))
       {
           return = base.OnBackButtonPressed();
       }
   }
   catch (Exception ex)
   {
       ExceptionExtension.TrackError(ex);
       return false;
   }
   return true;
}

UPDATE - Actually -- using the return does not actually navigate back the back a page. It appears it simply puts the app into the background, which in my case was what I wanted. But to be clear it does not navigate back one page. This might be due to the fact the Shell navigation does not populate the navigation stack but I am not sure.

1

There are 1 answers

1
FreakyAli On BEST ANSWER

If you want to trigger the default behavior just call the default method:

return base.OnBackButtonPressed();