Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice for handling exceptions when using command binding in WPF?

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?

like image 831
Jakob Christensen Avatar asked Dec 11 '09 12:12

Jakob Christensen


People also ask

How do you handle exceptions in WPF?

Start by creating a new WPF project with the name WPFExceptionHandling. Drag one textbox from the toolbox to the design window. The following XAML code creates a textbox and initializes it with some properties. Here is the file reading with exception handling in C#.

Is throwing exception good practice?

The short answer is NO. You would throw an exception if the application can't continue executing with the bad data. In your example, the logic is to display an error message on the front end and Option 2 is the cleaner method for achieving this requirement.

When should you use exception handling?

Use exceptions when the code that handles the error is separated from the code that detects the error by one or more intervening function calls. Consider whether to use error codes instead in performance-critical loops, when code that handles the error is tightly coupled to the code that detects it.


1 Answers

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

like image 103
Anvaka Avatar answered Dec 28 '22 07:12

Anvaka