Develop a Customized MessageBox in .NET MAUI

Massage Box

A message box, also known as a dialog or alert box, serves various functions within software applications, each with specific requirements aimed at improving user interaction. Here's an overview of these functions and their associated requirements:

Various types of message boxes

1. Informational Messages

Purpose: To present essential information or notifications to the user.

Importance: Users must be informed about critical events, updates, or changes occurring within the application.

2. Confirmation Dialogs

  • Purpose: To confirm user intent before executing critical actions (e.g., deleting a file).
  • Importance: Confirming user intent reduces the likelihood of accidental or irreversible actions, ensuring users are aware of the consequences.

In MAUI making a custom message box can be a challenging task. This can effortlessly be accomplished with the assistance of the Nuget bundle of “CustomControls.MAUI.MessageBox”.I am the proprietor of this package which makes a difference for users to make a completely customized message box of over said types. With this bundle, I am giving users distinctive properties that make a difference in setting diverse properties for messageBox.

These properties define the customization options for a message box in an MAUI application.

  • CustomMessageBoxTextColor: Specifies the text color inside the message box. In this case, it's set to white.
  • CustomMessageBoxHeightRequest: Determines the height of the message box. Here, it's set to 250 units.
  • CustomMessageBoxWidthRequest: Specifies the width of the message box. It's set to 330 units in this example.
  • CustomMessageBoxBackgroundColor: Defines the background color of the message box. It's set to black (#000000).
  • CustomMessageBoxTitlePosition: Determines the position of the title within the message box. Here, it's set to center and expand. However, the user has the option to position the title on the left, center, or right.
  • CustomMessageBoxButtonBackgroundColor: Sets the background color of the buttons in the message box. It's set to white (#FFFFFF).
  • CustomMessageBoxButtonTextColor: Specifies the text color of the buttons in the message box. In this case, it's set to black (#000000).

These properties allow developers to customize the appearance of message boxes according to their application's design and branding requirements.

Implementation of the customized messageBox

Step 1. The user is required to create an MAUI project using Visual Studio.

Toolbox

Step 2. Add the NuGet package " CustomControls.MAUI.MessageBox " to your project by following these steps.

Nuget Package

Step 3. In MauiProgram, you should include the following line.

MAUI program

Step 4. To enable Modal Popup functionality, the user needs to register the setup in MauiProgram.cs as shown below

Model class

using CommunityToolkit.Maui;
using CustomControls.MAUI.MessageBox.AppPresentations.CommonSource;
using CustomControls.MAUI.MessageBox.AppPresentations.Utilities;
using CustomControls.MAUI.MessageBox;
using Microsoft.Extensions.Logging;

namespace MauiAppCustomPopupExample
{
    public static class MauiProgram
    {
        [Obsolete]
        public static MauiApp CreateMauiApp()
        {
            try
            {
                // Initial setup for MAUI messagebox[Application Level declaration]
                ModalMessageBoxConfigurationSetup.SetupModalMessageBox(
                  customMessageBoxTextColor: Color.FromArgb("#FFFFFF"),
                  customMessageBoxHeightRequest: 350,
                  customMessageBoxWidthRequest: 300,
                  customMessageBoxBackgroundColor: Color.FromArgb("#0000FF"),
                  customMessageBoxTitlePosition: LayoutOptions.CenterAndExpand,
                  customMessageBoxButtonBackgroundColor: Color.FromArgb("#FFFFFF"),
                  CustomMessageBoxButtonTextColor: Color.FromArgb("#000000")
                  );

                var builder = MauiApp.CreateBuilder();
                builder.UseMauiApp<App>().ConfigureFonts(fonts =>
                {
                    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                    fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
                });

                RegisterEssentials(builder.Services);
                RegisterPages(builder.Services);
                RegisterViewModels(builder.Services);

                builder.UseMauiCommunityToolkit(); // Registering for MAUI Popup

                var app = builder.Build();
                MauiServiceHandler.MauiAppBuilder = app;

                return app;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        static void RegisterPages(in IServiceCollection services)
        {
            services.AddTransient<MainPage>();
        }

        static void RegisterViewModels(in IServiceCollection services)
        {
            services.AddTransient<MainPageViewModel>();
            services.AddTransient<SelfModalMessageBoxViewModel>();
        }

        static void RegisterEssentials(in IServiceCollection services)
        {
            services.AddSingleton<IModalMessageBoxServiceHandler, ModalMessageBoxServiceHandler>();
        }
    }
}

Step 5. Users also have the option to create their own custom message box page, which I've named "SelfModalMessageBox." Through this approach, users can develop their own "Information" and "Confirmation" message boxes. For such custom message boxes, users need to implement their own functionalities for the self-created page.

private void SelfPopupCommand()
{
    SelfModalMessageBox myCustomPopup = new SelfModalMessageBox();

    // Message box method without using an instance.
    // ModalMessageBoxHandler.ShowOwnCustomPopup(myCustomPopup);

    // Method for injecting dependencies using a service for the message box.
    modalMessageBoxServiceHandler.ShowCustomOwnPopup(myCustomPopup);
}

Step 6. The modal popup can be opened and closed in two ways: either without creating an instance of a class or by using dependency injection through registering the service in the IoC container. This can be achieved by implementing the MVVM (Model-View-ViewModel) pattern and creating a view model for an MAUI view.

1. Without creating an instance of a call modal popup can be opened and closed by using the following functionalities.

To open a modal popup for an "Information" messagebox without creating an instance.

CustomAlertMessageBox customAlertMessageBoxWithoutInstance = ModalMessageBoxHandler.GetCustomMessageBox(
    messageTitle: "Demo",
    messageText: "Sample Information messageBox",
    messageBoxButtonText: "Ok"
);

customAlertMessageBoxWithoutInstance.ButtonEventHandler += (sender, obj) =>
{
    // Your event handling logic goes here
};

The GetCustomMessageBox method necessitates three parameters: "messageTitle," "messageText," and "messageBoxButtonText."

  • messageTitle: This field sets the title of the message box. If the user prefers not to include a title, they can leave this option blank.
  • messageText: Use this field to input the message intended for the user.
  • messageBoxButtonText: This enables the user to customize the text displayed on the button according to their needs.

The "customAlertMessageBoxWithoutInstance.ButtonEventHandler " offers the capability to capture the action triggered by the button. If desired, users have the option to utilize this feature for event capture.

To open a modal popup for a "Confirmation" messagebox without creating an instance.

CustomConfirmMessageBox customConfirmMessageBoxWithoutInstance = ModalMessageBoxHandler.GetConfirmationMessageBox(
    messageTitle: "Demo",
    messageText: "Test messagebox",
    affirmativeButtonText: "Ok",
    negativeButtonText: "Cancel"
);

customConfirmMessageBoxWithoutInstance.AffirmativeButtonEventHandler += (sender, obj) =>
{
};

customConfirmMessageBoxWithoutInstance.NegativeButtonEventHandler += (sender, obj) =>
{
};

The GetConfirmationMessageBox method necessitates four  parameters: "messageTitle", "messageText"," affirmativeButtonText " and " negativeButtonText."

  • messageTitle: This field sets the title of the message box. If the user prefers not to include a title, they can leave this option blank.
  • messageText: Use this field to input the message intended for the user.
  • affirmativeButtonText: This enables the user to customize the text displayed on the button according to their needs. This button is used for positive response.
  • negativeButtonText: This enables the user to customize the text displayed on the button according to their needs. This button is used for negative responses.

The " customConfirmMessageBoxWithoutInstance.AffirmativeButtonEventHandler " and " customConfirmMessageBoxWithoutInstance.NegativeButtonEventHandler " are designated for handling affirmative and negative responses, respectively.

By using a dependency injection service

To achieve this, users need to register the ModalMessageBoxServiceHandlerclass in the IOC container as shown below. This allows it to be injected into the view model to obtain an instance of this class.

services.AddSingleton<IModalMessageBoxServiceHandler, ModalMessageBoxServiceHandler>();

To open a modal popup for an "Information" Messagebox with dependency injection service

CustomAlertMessageBox customAlertMessageBox = modalMessageBoxServiceHandler.GetCustomMessageBox(
    messageTitle: "Demo",
    messageText: "Sample Information messageBox",
    messageBoxButtonText: "Show"
);

customAlertMessageBox.ButtonEventHandler += (sender, obj) =>
{
};

The GetCustomMessageBox method necessitates three parameters: "messageTitle," "messageText," and "messageBoxButtonText."

  • messageTitle: This field sets the title of the message box. If the user prefers not to include a title, they can leave this option blank.
  • messageText: Use this field to input the message intended for the user.
  • messageBoxButtonText: This enables the user to customize the text displayed on the button according to their needs.

The " customAlertMessageBox.ButtonEventHandler " offers the capability to capture the action triggered by the button. If desired, users have the option to utilize this feature for event capture.

To open a modal popup for a "Confirmation" Messagebox with dependency injection service.

CustomConfirmMessageBox customConfirmMessageBox = modalMessageBoxServiceHandler.GetConfirmationMessageBox(
    messageTitle: "Demo",
    messageText: "Do you want to continue?",
    affirmativeButtonText: "YES",
    negativeButtonText: "CANCEL"
);

customConfirmMessageBox.AffirmativeButtonEventHandler += (sender, obj) =>
{
};

customConfirmMessageBox.NegativeButtonEventHandler += (sender, obj) =>
{
};

The GetConfirmationMessageBox method necessitates four  parameters: "messageTitle" ,"messageText", " affirmativeButtonText " and " negativeButtonText."

  • messageTitle: This field sets the title of the message box. If the user prefers not to include a title, they can leave this option blank.
  • messageText: Use this field to input the message intended for the user.
  • affirmativeButtonText: This enables the user to customize the text displayed on the button according to their needs. This button is used for positive response.
  • negativeButtonText: This enables the user to customize the text displayed on the button according to their needs. This button is used for negative responses.

The "customConfirmMessageBox.AffirmativeButtonEventHandler " and " customConfirmMessageBox.NegativeButtonEventHandler " are designated for handling affirmative and negative responses, respectively.

Step 7. The look of different MessageBoxes are as follows.

//Information MessageBox

Project demo

//Confirmation MessageBox

Confirmation MessageBox

 

//Self Defined MessageBox

 Self Defined MessageBox

 

Repository path: https://github.com/OmatrixTech/MauiAppCustomPopupExample


Similar Articles