How to deal with custom dialogs/popups?

This article explains how to integrate Popup control from the CommunityToolkit.Maui

Imperative approach

You can show a Popup using code like this:

public static class PopupManager
{
    class PopupVisualContainer : ContentView
    {
        public void Unmount()
        {
            //this is only required if you want to attach some code when the popup is closed
            base.OnUnmount();
        }
    }

    static Popup? _sheet;
    static PopupVisualContainer? _popupVisualContainer;
    private static ITemplateHost? _templateHost;

    public static async Task ShowPopupAsync(this MauiControls.Page? page, 
        Func<VisualNode> contentRender, 
        Action<PopupOptions>? configureOptionsAction = null, 
        CancellationToken cancellationToken = default)
    {
        if (page == null)
        {
            return;
        }

        if (_sheet != null)
        {
            return;
        }

        _popupVisualContainer = new PopupVisualContainer()
        {
            contentRender()
        };

        _templateHost = TemplateHost.Create(_popupVisualContainer);

        _sheet = new Popup
        {
            Content = (MauiControls.View)_templateHost.NativeElement!
        };

        PopupOptions? options = null;
        if (configureOptionsAction != null)
        {
            options = new PopupOptions();
            configureOptionsAction(options);
        }

        await page.ShowPopupAsync((MauiControls.View)_templateHost.NativeElement!, options, cancellationToken);

        _sheet = null;
        _templateHost = null;
    }
}

And, in the following example, we use it to create Alert and Confirmation dialogs:

Declarative approach

This solution is for the CommunityToolkit.Maui Popup:

and this is how you can use it in your components:

CommunityToolkit MAUI Popup

Last updated

Was this helpful?