Finally, after a couple of years of take, take, take; I’ve made a contribution to MahApps. Working in a financial institution it’s not always easy to commit back to open source projects, so with a little bit of out-of-hours work I’ve solved a little problem I’ve seen a few people asking: “how do you use MahApps dialog boxes in an MVVM setup?” And now my conscience is clear. 😉

Now You Can Launch a Dialog Box From a View Model.

There’s a couple of simple things you have to do:

1) Use an attached property in your Window to register your view model with the dialog sub-system.

Assuming your View’s DataContext is set to the view model from where you want to launch the dialog, add these attributes:

<Controls:MetroWindow xmlns:Dialog="clr-namespace:MahApps.Metro.Controls.Dialogs;assembly=MahApps.Metro" Dialog:DialogParticipation.Register="{Binding}" >

2) Grab & Use DialogCoordinator to open dialogs.

You can instantiate DialogCoordinator directly, or, good citizens will probably want to inject in the interface IDialogCoordinator into their view model. This will play nicely with TDD, and is agnostic to whatever DI framework you may be using.

Without a DI framework you could just do something like this:

new MainWindowViewModel(DialogCoordinator.Instance);

Opening up a dialog from your view model is now easy, using the IDialogCoordinator instance. To most methods the first parameter named “context” will typically be your view model. This is how the coordinator will match the view model to the window (with what was registered in step 1) and display the dialog. If you have multiple windows open, the dialog will display on the correct window. Show your dialog from inside your view model just like this:

_dialogCoordinator.ShowMessageAsync(this, "Message from VM", "MVVM based dialogs!")

If you want to see this in action and follow the code through open up the MahApps MetroDemo project (part of the MahApps source code), and launch from the “Dialogs” Menu:

This should make it into release 1.2.0.