views:

191

answers:

2

I am using the MVVM pattern for a WPF application. In several places I bind commands to input elements in the views as in the following XAML:

<Button Command="{Binding TheClickCommand}" >Click</>

What is the best practice for handling exceptions thrown when the command is executed in my viewmodel - i.e. what is the best way to inform the view that something is wrong? Can I use the IDataErrorInfo pattern or is there some other built-in pattern for this scenario?

A: 

The easiest answer is to simply pop a message box. A more sophisticated approach might be to use a notification service, which displays the message to the user in a manner appropiate to you app, but can be mocked out with a fake service for unit testing.

Ian Oakes
But should I put an event on my viewmodel and let the view listen to that event or what is the best way?
Jakob Christensen
Not unless the view needs to provide some specialized error handling. Mostly you will want to inform the user of what the error was. The main purpose of view models is to remove presentation logic from the view.
Ian Oakes
+1  A: 

Hi Jakob.

I hate this answer, but it really depends on a context.

Today I may use IoC, to get ILoggerService or INotificationSerivce or both and do the stuff when something went wrong. Tomorrow I may be happy with raw MessageBox.Show() somewhere in the DispatcherUnhandledException event handler. Or maybe I will write my own attached property ala

<Button loc:Commanding.ExceptionAwareCommand="{loc:CommandExtension 
          Command={Binding TheClickCommand}, 
          FallBackCammand={Binding ErrorHandlerCommand}}" />

and live with it...

Probably the answer may go like this: "Choose the best method to communicate between two classes and use it". Sorry for being non concrete... Maybe somebody else will be more specific.

NB: Interfaces' names, provided in the answer are not WPF standard. I use them just as an example.

Cheers

Anvaka
The interface names may not be a standard, but they seem to be emerging as a convention.
Ian Oakes
Although I was hoping for a more concrete answer, I guess your answer is as close as it gets. Thanks :-)
Jakob Christensen