views:

828

answers:

3

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?

+8  A: 

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.

HTH, Kent

Kent Boogaart
+1: Also, an alternative to using a ServiceLocator would be to use Dependency Injection to inject the IMessageService into the VMs as needed.
Reed Copsey
Because of the decoupling from the presentation layer you are able to unit test your ViewModel.
jbe
+6  A: 

Have a look at Josh Smith's excellent MVVM Foundation on Codeplex. Specifically, have a look at the Messenger class, a lightweight way of passing messages between various ViewModel objects who do not need to be aware of each other.

Also, I don't believe there is a hard-and-fast rule on "No code in the View", although it's best to be avoided if possible... remember that your XAML is simply .net code written in a declarative syntax; the code-behind is just C# or VB.net to supplement that (if absolutely necessary!)

IanR
+1 for the bit about ignoring the "no code in view" rule. It's more of a guideline anyway. :)
Cameron MacFarland
+1  A: 

You might also like to just put an ErrorMessage string property on your ViewModel class that your View can bind to.

wizlb