Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MAUI.NET display a pop up on back button pressed

Tags:

c#

maui

I'm trying to display a popup when the user hits the back button in a MAUI app.

I'm finding it tricky as the DisplayAlert is an asynchronous method that's needs to be awaited, but the override for OnButtonPressed is synchronous.

If I try and dispatch the alert in a separate awaitable task, it will show. But the App will still navigate away as it's not awaiting it.

I can't see any way to override the OnButtonPressed asynchronously.

Ideally I'm trying to do something like this:

protected override bool OnBackButtonPressed()
{
    var leave = await DisplayAlert("Leave lobby?", "Are you sure you want to leave the lobby?", "Yes", "No");

    if (leave)
    {
        await handleLeaveAsync();
        return base.OnBackButtonPressed();
    }
    else
    {
        return false;
    }
}

Any ideas? Thanks!

like image 736
Alex Avatar asked Oct 24 '25 17:10

Alex


1 Answers

Thanks @Jason for posting a link to similar problem in Xamarin, this works in MAUI and will stop the page from navigating away, however with this implementation we're unable to use the base behaviour.

This may be a problem if you rely on your navigation history as you now instruct the app where to navigate if they confirm, you will require more code to preserve and retrieve the history to navigate back to the previous screen.

protected override bool OnBackButtonPressed()
{
    Dispatcher.Dispatch(async () => 
    { 
        var leave = await DisplayAlert("Leave lobby?", "Are you sure you want to leave the lobby?", "Yes", "No"); 
        
        if (leave) 
        { 
            await handleLeaveAsync(); 
            await Navigation.PushAsync(new MainPage()); 
        } 
    }); 
    
    return true;
}
like image 120
Alex Avatar answered Oct 26 '25 07:10

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!