WPF MVVM dialog example

Oll picture Oll · Nov 3, 2009 · Viewed 37k times · Source

Does anyone have any examples of showing a window dialog using MVVM (Prism)? - for example a configuration settings window when a command is executed.

All of the examples I've seen use the mediator pattern which is fine, but they also all have a reference to the view in the view model which is not ideal (we're using DataTemplates)

Thanks

Answer

Cameron MacFarland picture Cameron MacFarland · Nov 6, 2009

I would use a service to display the dialog. The service can then also link views with viewmodels.

public interface IDialogService {
    void RegisterView<TView, TViewModel>() where TViewModel:IDialogViewModel;
    bool? ShowDialog(IDialogViewModel viewModel);
}

public interface IDialogViewModel {
    bool CanClose();
    void Close();
}


RegisterView just links the view type with the ViewModel type. You can set up these links in the module initialization. This is simpler than trying to get modules to register datatemplates in the top layer of your application.

ShowDialog Shows the ViewModel you want to display. It returns true, false and null for close just like the Window.ShowDialog method. The implementation just creates a new view of type TView from your container, hooks it up to the provided ViewModel, and shows it.

IDialogViewModel provides a mechanism for the ViewModel to do verification and cancel the closing of the dialog.

I have a standard dialog window, with a content control in it. When ShowDialog is called it creates a new standard dialog, adds the view to the content control, hooks up the ViewModel and displays it. The standard dialog already has [OK] and [Cancel] buttons with the appropriate logic to call the right methods from IDialogViewModel.