MVVM Tips: How to show a message box or dialog in MVVM Silverlight?

The key to successfully separating the concerns of your application is all in the abstraction.

Of course we do not want to call MessageBox.Show() from within our ViewModel as this will not allow us to automatically test it. We will need to abstract the call to MessageBox.Show() so that you can swap it out for testing. A simple way to do this is to use a service implementing an interface that we can swap out depending on whether we are testing or running the application.

public interface IMsgBoxService
    ShowNotification(string message);
    bool AskForConfirmation(string message);
    //... etc

public class MsgBoxService : IMsgBoxService
    public void ShowNotification(string message)
        MessageBox.Show(message, "Notification", MessageBoxButton.OK)

    public bool AskForConfirmation(string message)
            MessageBoxResult result = MessageBox.Show(message, "Are you sure?", MessageBoxButton.OKCancel);
            return result.HasFlag(MessageBoxResult.OK);

Now that we have implemented our message box service we just need to get an instance of it and call the appropriate method in our ViewModel

private IMsgBoxService messageService;
public TestViewModel(IMsgBoxService msgboxService)
   this.messageService = msgboxService;

public void SomeMethod()

There it is, a few lines of code and you have a message box you can safely use throughout your application in a MVVM way that will allow for testability and seperation of concerns.

Lots more MVVM tips to come so subscribe if you would like to stay updated. Thanks!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s