Question

I am writing a WPF application using the MVVM design pattern. I wanted to know the best possible(read "MVVM Complaint") way of doing this. Also be aware that all the code in my view model doesn't run on the UI thread. Currently I am accessing the Dispatcher in the VM using App.Current.Dispatcher and then calling the MessageBox.Show() on it.

Was it helpful?

Solution

You should create following services

IMessageBoxService \\ Exposes Show(string Title, String Caption)
IDispatcherService \\ Exposes Dispatch(Action action), Register(Dispatcher)

Then Create WPF specific implementation as

MessageBoxService (or WPFMessageBoxService if you wish)
DispatcherService

Register these to the DI/IoC container used in the application (such as Unity/MEF/Windsor)

For the dependent View Model, Pass the service through constructor like

public MainViewModel(IMessageBoxService messageBoxService, IDispatcherService dispatcherService)

Now you can use messageBoxService/dispatcherService to invoke message box through ViewModel on Dispatcher.

MessageBox example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top