Álvaro García
Álvaro García

Reputation: 19396

How to override the device back button in a MAUI application?

I have an application in MAUI and a page in which I would like to override the back button of the button, to check if some parameters are set or not before allow to go back.

I have seen this code in the documentation:

<Shell.BackButtonBehavior>
    <BackButtonBehavior Command="{Binding VBackCommand}" />
</Shell.BackButtonBehavior>

And it works, the command in my view model is execuetd, but I can back without running the command if I use the back button of the system.

Are there some way to intercept the back button of the system?

Thanks.

Upvotes: 0

Views: 6789

Answers (1)

Liqun Shen-MSFT
Liqun Shen-MSFT

Reputation: 8290

I made a demo to control the BackButtonBehavior of system back button.

Suppose there's a button click event handler that we use to navigate from MainPage to another page:

private void OnCounterClicked(object sender, EventArgs e)
{
    Shell.Current.Navigation.PushAsync(new NewPage1());
}

And in NewPage1 xaml, you have defined the BackButtonBehavior:

<Shell.BackButtonBehavior>
    <BackButtonBehavior Command="{Binding VBackCommand}" />
</Shell.BackButtonBehavior>

So when press back button, the command set in ViewModel will execute. And you can control the Navigation by sending a message using MessagingCenter or WeakReferenceMessenger.

public Command VBackCommand
{
    get
    {
        return new Command(() =>
        {
            Console.WriteLine("123");
            // if parameter are set, you could send a message to navigate
            if (ParameterSet)
            {
                MessagingCenter.Send<NewPageViewModel>(this, "Hi");
            }
        });
    }
}

So in NewPage1.cs, just subscribe the message and popasync

public NewPage1()
{
    InitializeComponent();
    this.BindingContext = new NewPageViewModel();
    MessagingCenter.Subscribe<NewPageViewModel>(this, "Hi", (sender) =>
    {
        Shell.Current.Navigation.PopAsync();
    });
}

Is this effect what you want? If you have any question, feel free to ask.

Upvotes: 2

Related Questions