How To Generate a Pop Up in .Net Maui using the Maui Community Toolkit Part .1

How To Generate a Pop Up in .Net Maui using the Maui Community Toolkit Part .1

If you've been wondering how to generate a popup view within your .Net Maui App this is how you can do it.

Firstly we are going to need to add the Maui Community Toolkit using Nuget Manager.

image.png

Secondly, create a new ContentPage or ContentView, it doesn't matter. We are going to override it anyway. Avoid naming it PopUp, this can cause confusion with the name of the Popup Class built into Maui Community Toolkit.

By Default if you create a Content View it will look something like this:

In C#:

public partial class popupdialog : ContentView
{
    public popupdialog()
    {
        InitializeComponent();
    }
}

In XAML:

<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

             x:Class="PopUpSample.Views.popupdialog">
    <VerticalStackLayout>
        <Label 
            Text="Welcome to .NET MAUI!"
            VerticalOptions="Center" 
            HorizontalOptions="Center" />
    </VerticalStackLayout>
</ContentView>

To convert it to a PopUp we are going to change the 'ContentView' in to 'CommunityToolkit.Maui.Views.Popup' so our PopUp C# codebehind should now look something like this.

public partial class popupdialog : CommunityToolkit.Maui.Views.Popup
{
    public popupdialog()
    {
        InitializeComponent();
    }
}

In XAML we also need to change the view to a Popup, in order to do that ensure that you add the 'xmlns:toolkit="schemas.microsoft.com/dotnet/2022/maui/tool.."' namespace to your XAML sheet, then change 'ContentView' to 'toolkit:Popup'. Your XAML code behind should look like this now.

<toolkit:Popup xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
             x:Class="PopUpSample.Views.popupdialog">
    <VerticalStackLayout>
        <Label 
            Text="Welcome to .NET MAUI!"
            VerticalOptions="Center" 
            HorizontalOptions="Center" />
    </VerticalStackLayout>
</toolkit:Popup>

To show our popup you simply add the following to the method where the popup action is fired.

var popup = new popupdialog ();
await PopupExtensions.ShowPopupAsync<popupdialog >(this, popup);

and that's it, thanks for reading. Next time I'll show you how to return a result or series of result as well as all the other cool features of Popups in dotnet maui