MahApps MessageBoxes using MVVM

MoonKnight picture MoonKnight · Feb 28, 2014 · Viewed 20.1k times · Source

Simple question for the MahApps Merry Men. I have implemented an application using your great metro styled controls using Caliburn.Micro for the MVVM stuff. The new message dialogs look great, but currently there is not clear way of launching these dialogs with out writing my own wrapper (which I am not against). However, has this been done or is there something I missing so that I can invoke a message box from a view model without any fuss?

Thanks for your time.

Answer

James Willock picture James Willock · Jun 1, 2015

As of 1.1.3-ALPHA* (to become 1.2.0) MahApps provides a helper to launch dialogs from a VM, which works in a multiple Window setup:

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/inject DialogCoordinator:

new MainWindowViewModel(DialogCoordinator.Instance);

3) Show your dialog from the view model. Use "this" as the context so MahApps can marry your view model to the correct window:

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