Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM Exception Handling

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?

like image 493
Jake Pearson Avatar asked Aug 26 '09 18:08

Jake Pearson


1 Answers

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.

like image 146
Kent Boogaart Avatar answered Oct 03 '22 16:10

Kent Boogaart