Developing a Customized MessageBox in Xamarin

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 include

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 Xamarin making a custom message box can be a challenging tasks.This can effortlessly be accomplished with the assistance of Nuget bundle of “Xamarin.Custom.MessageBox”.I am the proprietor of this package which makes a difference users to make a completely customized message boxes of over said types.By this bundle I am giving users distinctive properties which makes a difference in setting diverse properties for messageBox.

These properties define the customization options for a message box in a Xamarin 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 custom messageBox

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

Step 2. Add the NuGet package "Xamarin.Custom.MessageBox" to your project by following these steps:

NuGet package Xamarin.Custom.MessageBox

Step 3. In Android, you should include the following line in the "MainActivity.cs" file to register "Rg.Plugins.Popup.Popup.Init(this);":

Rg.Plugins.Popup.Popup.Init(this);

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

Modal Popup functionality

using Microsoft.Extensions.DependencyInjection;
using System;
using Xamarin.Custom.MessageBox;
using Xamarin.Forms;
using XamarinMessageBox.ViewModels;
namespace XamarinMessageBox
{
    public partial class App : Application
    {
        public static IServiceProvider ServiceProvider { get; private set; }
        public App()
        {
            InitializeComponent();
           //Register modal popup setup
           ModalMessageBoxConfigurationSetup.SetupModalMessageBox(
           customMessageBoxTextColor: Color.White,
           customMessageBoxHeightRequest: 250,
           customMessageBoxWidthRequest: 330,
           customMessageBoxBackgroundColor: Color.FromHex("#000000"),
           customMessageBoxTitlePosition: LayoutOptions.CenterAndExpand,
           customMessageBoxButtonBackgroundColor: Color.FromHex("#FFFFFF"),
           CustomMessageBoxButtonTextColor:Color.FromHex("#000000")
           );
            // Initialize and configure services
            var serviceCollection = new ServiceCollection();
            ConfigureServices(serviceCollection);
            // Build the service provider
            ServiceProvider = serviceCollection.BuildServiceProvider();
            MainPage = new AppShell();
        }
        private void ConfigureServices(IServiceCollection services)
        {
            // Register your services here
            services.AddSingleton<IModalMessageBoxServiceHandler, ModalMessageBoxServiceHandler>();
            services.AddSingleton<AboutViewModel>();
            services.AddSingleton<SelMessageBoxViewModel>();
        }
        protected override void OnStart()
        {
        }
        protected override void OnSleep()
        {
        }
        protected override void OnResume()
        {
        }
    }
}

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 async Task OpenSelfModalMessageBox()
{
    //Dependency injection service
    await modalMessageBoxServiceHandler.ShowSelfCreatedMessageBox(new SelMessageBox());
    //Wthout instance method
    //ModalMessageBoxHandler.ShowSelfCreatedMessageBox(new SelMessageBox());
}

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 a Xamarin 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.

Device.BeginInvokeOnMainThread(async () =>
{
    CustomAlertMessageBox customAlertMessageBox = await ModalMessageBoxHandler.GetCustomMessageBox(messageTitle: "Information", messageText: "Demo testing mesagebox", messageBoxButtonText: "Demo");
    customAlertMessageBox.OkButtonEventHandler += (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.OkButtonEventHandler" 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 customConfirmMessageBox = await ModalMessageBoxHandler.GetConfirmationMessageBox(messageTitle: "Do you want to continue?", messageBoxFirstButtonText: "Ok", messageBoxButtonSecondText: "Cancel");
    customConfirmMessageBox.YesButtonEventHandler += (sender, obj) =>
    {
    };
    customConfirmMessageBox.NoButtonEventHandler += (sender, obj) =>
    {
    };
});

The GetConfirmationMessageBox method necessitates four  parameters: "messageTitle", "messageText","messageBoxFirstButtonText" and "messageBoxButtonSecondText."

  • 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.
  • messageBoxFirstButtonText: Enables the user to customize the text displayed on the button according to their needs. This button is used for positive response.
  • messageBoxButtonSecondText: Enables the user to customize the text displayed on the button according to their needs. This button is used for negative response.

The "customConfirmMessageBox.YesButtonEventHandler" and "customConfirmMessageBox.NoButtonEventHandler" are designated for handling affirmative and negative responses, respectively.

2. By using dependency injection service

To achieve this, users need to register the CustomMessageBoxService class 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

Device.BeginInvokeOnMainThread(async () =>
{
    CustomAlertMessageBox customAlertMessageBox = await modalMessageBoxServiceHandler.GetCustomMessageBox(messageTitle: "Information", messageText: "Testing custom messagebox", messageBoxButtonText: "Okay");
    customAlertMessageBox.OkButtonEventHandler += (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.OkButtonEventHandler" 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 = await modalMessageBoxServiceHandler.GetConfirmationMessageBox(messageTitle: "Confirmation messagebox", messageText: "Do you want to continue?", messageBoxFirstButtonText: "Yes", messageBoxButtonSecondText: "No");
customConfirmMessageBox.YesButtonEventHandler += (sender, obj) =>
{
};
customConfirmMessageBox.NoButtonEventHandler += (sender, obj) =>
{
};

The GetConfirmationMessageBox method necessitates four  parameters: "messageTitle" ,"messageText", "messageBoxFirstButtonText" and "messageBoxButtonSecondText."

  • 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.
  • messageBoxFirstButtonText: Enables the user to customize the text displayed on the button according to their needs. This button is used for positive response.
  • messageBoxButtonSecondText: Enables the user to customize the text displayed on the button according to their needs. This button is used for negative response.

The "customConfirmMessageBox.YesButtonEventHandler" and "customConfirmMessageBox.NoButtonEventHandler" are designated for handling affirmative and negative responses, respectively.

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

Information MessageBox

Information MessageBox in Xamarin

Confirmation MessageBox

Confirmation MessageBox in Xamarin

Self Defined MessageBox

Self Defined MessageBox in Xamarin

Repository pathhttps://github.com/OmatrixTech/XamarinMessageBox


Similar Articles