Over the past couple weeks I’ve been working on a newer WPF application that is using the MVVM Light Toolkit and thus the MVVM pattern. Like everything in this field, there are some great attributes of the pattern and some that are not so great. But all in all the MVVM Light Toolkit has some great resources to help you get along. I would really recommend taking a look, Laurent Bunion has done a really nice job of putting together a framework that is pretty easy to use and understand.
The only real hang-up I’ve had thus far is in displaying modal windows and dialogs. After some searching there are a couple good posts in the discussion forums about how to use the messaging framework (which I’ll admit, I’m no expert at) to display dialogs in a MVVM friendly way.
After reading through his sample app it all made sense, but what I really wanted was an example of displaying a modal window where some work was done, and information was then passed back to the main ViewModel after the modal was closed. I put together a quick example of one way to do this. Hopefully it’ll be useful to you if you’re in the same boat. Here’s the code.
At the center of the example is the ModalMessage<TViewModel> class. The idea is to use this in your main window to define your message that sends a ViewModel to the recipient.
[csharp]Messenger.Default.Register<ModalMessage<ModalWindowViewModel>>(
this,
msg =>
{
var dialog = new ModalWindow(msg.ViewModel);
var result = dialog.ShowDialog();
msg.Callback(result ?? false, msg.ViewModel);
});[/csharp]
The recipient (the modal window) then uses this ViewModel to present data, and ultimately send the object back via the msg.Callback() method.
While the message is registered in the main window codebehind, the whole process is kicked off, and the results received in the MainViewModel class.
[csharp]private void ShowDialog()
{
var vm = new ModalWindowViewModel()
{
DisplayText = "Please send a response!"
};
var message = new ModalMessage<ModalWindowViewModel>(vm, ShowDialogCallback);
Messenger.Default.Send(message);
}
private void ShowDialogCallback(bool confirmed, ModalWindowViewModel returnedVm)
{
if (confirmed)
{
this.Welcome = returnedVm.Response;
}
}[/csharp]
MvvmModalSample.zip