Skip to content

Custom message box

FantasticFiasco edited this page Dec 13, 2017 · 2 revisions

To show a custom message box start by implementing IMessageBox.

public class CustomMessageBox : IMessageBox
{
    ...
}

Next up is the implementation of the custom framework dialog factory, responsible for creating framework dialogs opened by DialogService.

public class CustomFrameworkDialogFactory : DefaultFrameworkDialogFactory
{
    public override IMessageBox CreateMessageBox(MessageBoxSettings settings)
    {
        return new CustomMessageBox(settings);
    }
}

At this point we have a complete implementation of a custom framework dialog factory. Next up is providing it to DialogService.

How that is done depends on the application. If you are using an IoC container you would configure the container to inject the factory when the container is resolving the dialog service. If you are running on bare metal you would configure this wherever you initialize your application.

For this application, lets assume that we are creating the dialog service in MainWindowViewModel.

public class MainWindowViewModel : INotifyPropertyChanged
{
    private readonly IDialogService dialogService;

    public MainWindowViewModel()
    {
        var frameworkDialogFactory = new CustomFrameworkDialogFactory();
        dialogService = new DialogService(frameworkDialogFactory: frameworkDialogFactory);
    }

    ...
}

We now have the dialog service configured to use the custom framework dialog factory. The following steps are the same for standard message boxes.

Register the view by decorating the XAML with the attached property DialogServiceViews.IsRegistered.

<UserControl
    x:Class="DemoApplication.Features.MessageBox.Views.MessageBoxTabContent"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:md="https://github.com/fantasticfiasco/mvvm-dialogs"
    md:DialogServiceViews.IsRegistered="True">

</UserControl>

In the view model, open the dialog by calling IDialogService.ShowMessageBox.

public class MessageBoxTabContentViewModel : INotifyPropertyChanged
{
    private readonly IDialogService dialogService;
  
    public MessageBoxTabContentViewModel(IDialogService dialogService)
    {
        this.dialogService = dialogService;
    }
  
    private void ShowMessageBox()
    {
        dialogService.ShowMessageBox(
            this,
            "This is the text.",
            "This Is The Caption",
            MessageBoxButton.OKCancel,
            MessageBoxImage.Information);
    }
}