MVVM Exception Handling

Jake Pearson picture Jake Pearson · Aug 26, 2009 · Viewed 7.7k times · Source

I have a WPF Application that I have been trying to write in the MVVM style. If an Exception is thrown (like when a document is opened), I would like to display a MessageBox. Easy to do, but my code doesn't feel quite right because the MessageBox.Show call is in the ModelView. I thought that sort of thing is supposed to live in the View, but I'm not supposed to put code in the View.

So the question really can be distilled down to what is the suggested way to display a MessageBox in MVVM?

Answer

Kent Boogaart picture Kent Boogaart · Aug 26, 2009

Use a service:

public void SomeMethodInYourViewModel()
{
    try
    {
        DoSomethingDangerous();
    }
    catch (Exception ex)
    {
        ServiceLocator.Resolve<IMessageService>().ShowMessage(ex.Message);
    }
}

You have now decoupled your VMs from the presentation of messages. You may even decide not to use the standard (ugly) message boxes at all and that won't affect your VMs.