Search code examples
c#.net-8.0back-buttonmudblazormaui-blazor

Call OnBackButtonPressed() in ComponentBase class in Maui.Net


I am building a mobile app (Android and iOS) using .NET MAUI Blazor Hybrid with .NET 8. For the frontend UI, I am using MudBlazor, and I have implemented MudDialog in several places. My issue is that when the back button on the mobile device is pressed, it navigates to the previous page instead of closing the MudDialog.

I am aware of the protected override bool OnBackButtonPressed() function, but it can only be called in a class that inherits from ContentPage. My classes inherit from ComponentBase because I need to use StateHasChanged() and OnParametersSetAsync() functions.

How can I close a MudDialog when the back button is pressed on a mobile device without navigating to the previous page? Is there a way to call OnBackButtonPressed() in a ComponentBase class? Alternatively, is there a method using JavaScript to trigger the back button press event and prevent navigation to the previous page, thereby closing the MudDialog instead?

Any guidance or suggestions would be greatly appreciated.

For instance, This is my button to open Dialog <MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="CreateNew"> Open Dialog</MudButton> CreateNew Function is this:

public async Task CreateNew()
    {
        var parameters = new DialogParameters();

        parameters.Add("TempId", TempId);
        var options = new DialogOptions() { CloseOnEscapeKey = true, NoHeader = false, Position = DialogPosition.Center, CloseButton = true, FullWidth = true, MaxWidth = MaxWidth.Medium, DisableBackdropClick = true };

        await DialogService.Show<Dialog>("Create New Support Request", parameters, options).Result;
    }

And My dialog file is this:

@inject ISnackbar Snack

<MudDialog>
    <TitleContent>
        <MudStack Row AlignItems="AlignItems.Center">
            <MudText Color="Color.Info" Typo="Typo.subtitle2">Start New</MudText>
        </MudStack>
    </TitleContent>
    <DialogContent>
        <MudGrid>
            <MudItem xs="12" sm="6">
                <MudTextField FullWidth Margin="Margin.Dense" Variant=Variant.Outlined Label="Subject" MaxLength="100" T="string" @bind-Value="title"></MudTextField>
            </MudItem>
        </MudGrid>
        <MudTextField Class="mb-4" FullWidth Margin="Margin.Dense" Variant=Variant.Outlined Label="Message" Lines=5 T="string" @bind-Value="msg"></MudTextField>
    </DialogContent>
    <DialogActions>

        <MudButton Disabled="loading" Color="Color.Primary" OnClick="Create">
            Send
            @if (loading == true)
            {
                <MudProgressCircular Size="Size.Small" Color="Color.Info" Indeterminate="true" />
            }
        </MudButton>



    </DialogActions>
</MudDialog>
@code {

    [Parameter]
    public Template TempId { get; set; }
    bool loading = false;
    string title = "", msg = "";
    [CascadingParameter] MudDialogInstance MudDialog { get; set; }


    void close()
    {
        MudDialog.Close();
    }

    public async Task Create()
    {
        //create code
    }
}
```

Solution

  • How can I close a MudDialog when the back button is pressed on a mobile device without navigating to the previous page?

    You can use NavigationLock, a component is introduced in .NET 7 that provides a way to control or prevent navigation events in Blazor, something that was previously more difficult to pull off effectively.

    You can now provide a handler for internal events and enable a flag:canNavigateBack to control whether you can navigate back or not when the back button is pressed.

    <NavigationLock OnBeforeInternalNavigation="OnBeforeInternalNavigation" />
    
    private bool canNavigateBack = false;
    
    
    private async Task OnBeforeInternalNavigation(LocationChangingContext locationChangingContext)
    {
           if (!canNavigateBack)
           {
               locationChangingContext.PreventNavigation();
               //you can close MudDialog here
           }
    }
    

    Reference link:

    https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.routing.navigationlock?view=aspnetcore-8.0