maui icon indicating copy to clipboard operation
maui copied to clipboard

A single way to override the back button behavior

Open manuelelucchi opened this issue 4 years ago • 22 comments

Description

Right now, on both Xamarin Forms and Maui, there is no direct way to override the navbar back button behavior, while you can with phisical/software buttons (on android only) using the OnBackButtonPressed method.

I suggest to add on the Page (or even NavigationPage) a property to Enable or Disable the back button (be it on the navbar or phisical) and an overridable method/event to capture the back button when is pressed (regardless of the type/platform) similar on how someone did in this tutorial

Public API Changes

var page = new ContentPage();
page.IsBackButtonEnabled  = false; // It should be a dependency property for it being able to be binded
page.OnBackPressed += BackPressed; 
// or overriding it like it is at the moment but also including the navbar back button
// Also, why not a Command like BackPressedCommand to make it work better with MVVM?

Intended Use-Case

Right now you are not able to properly control how the user uses the back button without heavy customization

manuelelucchi avatar Apr 22 '22 10:04 manuelelucchi

How can this be done now?

Gibrid89 avatar Nov 23 '22 11:11 Gibrid89

@Gibrid89 in this linkhttps://learn.microsoft.com/en-us/dotnet/maui/fundamentals/shell/navigation?view=net-maui-7.0#back-button-behavior you can use this documentation, you have to paste the code in every xaml file you want it to be used

nielstoemen avatar Nov 30 '22 15:11 nielstoemen

@nielstoemen Thank you, it's interesting. But I use blazor, so I don't have shell navigation.

Gibrid89 avatar Dec 01 '22 06:12 Gibrid89

@Gibrid89 in this linkhttps://learn.microsoft.com/en-us/dotnet/maui/fundamentals/shell/navigation?view=net-maui-7.0#back-button-behavior you can use this documentation, you have to paste the code in every xaml file you want it to be used

Hi buddy, link doesn't work. Thank you.

drshark avatar Dec 06 '22 11:12 drshark

https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/shell/navigation?view=net-maui-7.0#back-button-behavior

i see, it worked when i posted it. you have to copy paste the link in the browser when you click on it github does weird things. don't know the reason

nielstoemen avatar Dec 06 '22 11:12 nielstoemen

https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/shell/navigation?view=net-maui-7.0#back-button-behavior

i see, it worked when i posted it. you have to copy paste the link in the browser when you click on it github does weird things. don't know the reason

Yes, with copy/paste it works. I didn't know this github bug, sorry.

drshark avatar Dec 06 '22 11:12 drshark

great than I'm sure it will work for most people, no problem

nielstoemen avatar Dec 06 '22 12:12 nielstoemen

@nielstoemen What If Im not using Shell but some other framework? Im checking out Prism.MAUI and for ContentPage I cant get <Shell.BackButtonBehavior> to work. Guess because Im not using Shell. Are developer forced to implement this on their own if not using Shell? :(

Ah ok. Im not sure if this should go here or to some MAUI discussion but funnsy stuff. I created a class based on NavigationPage and used it in navigation. Then suddenly somehow ContentPage.OnBackButtonPressed started catching Toolbar back button on Android. Huh.

Pastajello avatar Jan 07 '23 13:01 Pastajello

@Pastajello I personally dont have any experience with Prism.MAUI but you can maybe ask around on StackOverflow or in a dedicated discord server.

if you want to use a backbutton you can make this yourself, you can look for it online I'm sure there is documentation on it. otherwise ask on StackOverflow, there are plenty of people there who can and want to help

nielstoemen avatar Jan 09 '23 12:01 nielstoemen

Just implemented the renderer on the platforms (NavigationPageRenderer -> Android & NavigationRenderer -> iOS) and overrided OnPopViewAsync to intercept the action. This works for both back actions : hardware and software.

EricPucho avatar Sep 21 '23 08:09 EricPucho

@EricPucho I did what you did but am finding that on iOS the pop happens before OnPopViewAsync is called. Are you experiencing this?

rjgiven avatar Jan 24 '24 18:01 rjgiven

@rjgiven Not experienced this one, but try to catch the action based on page title (ie this.page.Title)

EricPucho avatar Jan 29 '24 19:01 EricPucho

Hello everyone, I have a .NET Maui application for iOS and Android. Just wanted to know of some methods that I can implement to override/intercept back button events. I have a navigation page that has a back button on it . Just want to intercept it to execute some custom logic. Please let me know of a "simple" way of doing this.

philm001 avatar Mar 01 '24 03:03 philm001

Android

using System;
using Android.Content;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android.AppCompat;

[assembly: ExportRenderer(typeof(NavigationPage), typeof(CustomNavigationPageRenderer))]
namespace MyProject.Droid.Renderers
{
    public class CustomNavigationPageRenderer : NavigationPageRenderer
    {
        public CustomNavigationPageRenderer()
        {
        }

        public CustomNavigationPageRenderer(Context context) : base(context)
        {
        }
        protected override Task<bool> OnPopViewAsync(Page page, bool animated)
        {
            if (page.Title != "MyPageName") return base.OnPopViewAsync(page, animated);
            //do actions here
            return base.OnPopViewAsync(page, animated);
        }
    }
}

iOS

using System.Threading.Tasks;
using System;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(NavigationPage), typeof(CustomNaviPageRenderer))]
namespace MyProject.iOS.Renderers
{
    public class CustomNaviPageRenderer : NavigationRenderer
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

        }
        protected override Task<bool> OnPopViewAsync(Page page, bool animated)
        {
            if (page.Title != "MyPageName") return base.OnPopViewAsync(page, animated);
            //do actions here
            return base.OnPopViewAsync(page, animated);
        }
        
    }
}

Just implemented the renderer on the platforms (NavigationPageRenderer -> Android & NavigationRenderer -> iOS) and overrided OnPopViewAsync to intercept the action. This works for both back actions : hardware and software.

EricPucho avatar Mar 13 '24 15:03 EricPucho

Maui platform needs more support for non-shell activities. I understand that Shell was a big effort to streamline a lot of things, but right now traditional way of doing things looks more a bit forgotten to me. We need BackButtonBehavior for Shell to work with NavigationPage.

bkaankose avatar Nov 18 '24 13:11 bkaankose

Did anyone find a working solution for .MAUI 9.0?

CleverSoftwarePoland avatar Mar 17 '25 12:03 CleverSoftwarePoland

Did anyone find a working solution for .MAUI 9.0?

I use this for .NET MAUI 8.0 in a custom BasePage class. If all navigation is handled through the NavigateTo() method, then NavigationLocationChanging with PreventNavigation == true corresponds to the back button.

[Inject]
protected Microsoft.AspNetCore.Components.NavigationManager navigationManager { get; set; }
 
 private IDisposable NavigationLocationChangingHandler;
 protected override async Task OnInitializedAsync()
 {
     await base.OnInitializedAsync();
     NavigationLocationChangingHandler = navigationManager.RegisterLocationChangingHandler(NavigationLocationChanging);
 }


public bool PreventNavigation { get; set; } = true;
protected ValueTask NavigationLocationChanging(LocationChangingContext context)
{
    if (this.PreventNavigation && !Disposed)
    {
        // This is the back button.
        context.PreventNavigation();       
    }
    
    return ValueTask.CompletedTask;
}

protected virtual void NavigateTo(string navigateTo)
{
    if (Disposed)
        return;
    this.PreventNavigation = false;
    navigationManager.NavigateTo(navigateTo);
}

protected bool Disposed;
protected override void Dispose(bool disposing)
{
    if (!Disposed)
    {
        if (disposing)
        {           
            if (NavigationLocationChangingHandler != null)
                NavigationLocationChangingHandler.Dispose();                                
        }
        Disposed = true;
    }
    // Call base class implementation.
    base.Dispose(disposing);
}

Gibrid89 avatar Mar 20 '25 09:03 Gibrid89

I managed to make it work with custom NavigationRenderer, it will invoke BackButtonPressed on Page so it will be the same behavior on iOS and Android.

public class NavigationPageRenderer : NavigationRenderer { public override UIViewController PopViewController(bool animated) { var navigationPage = Element as NavigationPage;

    var currentPage = navigationPage?.CurrentPage;

    if (currentPage != null && currentPage is Page)
    {
        HandleBackPressed((currentPage as Page), animated);

        return null; // Return null to stop navigation
    }
    else
    {
        return base.PopViewController(animated);
    }
}

private async void HandleBackPressed(Page contentPage, bool animated)
{
    bool shouldNavigate = contentPage.SendBackButtonPressed();

    if (!shouldNavigate)
    {
        await MainThread.InvokeOnMainThreadAsync(() =>
        {
            base.PopViewController(animated);
        });
    }
}

}

CleverSoftwarePoland avatar Mar 20 '25 13:03 CleverSoftwarePoland

@jfversluis We face the same problem as the commenters and I would propose a possible spec and, if possible, a pull request implementing it. How should I start with this?

My idea is to have an attached Property NavigationPage.BackButtonBehavior similar to the NavigationPage.BackButtonTitle property that controls how a page behaves if a back button (hardware or in the title bar) is pressed.

MFinkBK avatar May 13 '26 12:05 MFinkBK

@MFinkBK we have this one I think is also related: https://github.com/dotnet/maui/issues/31266

You might want to talk to @PureWeen. We're always interested in people helping out :) are you on the MAUIverse Discord by any chance? You can join on https://mauiverse.net/discord. There are people from our team on there which makes it a bit easier to go back and forth on this.

jfversluis avatar May 15 '26 15:05 jfversluis