WPF MessageBox with MVVM pattern? WPF MessageBox with MVVM pattern? wpf wpf

WPF MessageBox with MVVM pattern?


Have an interface IMessageBoxService as:

interface IMessageBoxService{    bool ShowMessage(string text, string caption, MessageType messageType);}

Create a WPFMessageBoxService class:

using System.Windows;class WPFMessageBoxService : IMessageBoxService{    bool ShowMessage(string text, string caption, MessageType messageType)    {        // TODO: Choose MessageBoxButton and MessageBoxImage based on MessageType received        MessageBox.Show(text, caption, MessageBoxButton.OK, MessageBoxImage.Information);    }}

In your ViewModel accept IMessageBoxService as a constructor parameter and inject WPFMessageBoxService using DI/IoC.

In the ViewModel, use IMessageBoxService.ShowMessage to show the MessageBox.

ShowMessageCommand = new DelegateCommand (    () => messageBoxService.ShowMessage(message, header, MessageType.Information));

Customize IMessageBoxService interface to your needs, and pick up a better name.


You could bind your messagebox control's visibility to the validation.

You will need a Bool To Visibility converter for this.

See here for using the built in converter:Binding a Button's visibility to a bool value in ViewModel