Viswanath Ramanan
Viswanath Ramanan

Reputation: 133

MVVM, Xaml, Command binding, Exception handling and Message Box

I'm currently developing a windows phone app. I know quite a bit about MVVM and its benefits. So I try my best to keep UI logic separate from the business logic. But I'm stumped on this one.

Say there is a Command in the ViewModel and UI is bound to this command through xaml. Hence I never call the execute function. Say this command is actually capable of throwing exceptions. I want to catch this and show a notification. The following is what came to my mind:

  1. Pass an interface to the command so that it can notify when something goes wrong. The class that implements this interface can hold the logic to show the message box. This works fine but breaks app globalization/localization. I want to store the error message in the AppResources.resx file, so that the appropriate error message will be picked when the default language is changed. I don't want to call AppResources from the command as I cannot test it if I add that to the Command which is in the viewmodel
  2. We can call the command from code behind, with a try catch and then the MessageBox can be shown directly based upon the exception.

I'm not very happy with either solutions. Is there a good way to handle exceptions on Commands that are bound to the UI? I saw that DispatchedUnhandledException, but will it to be domain specific? I don't want all exceptions to be caught at one place to notify the user. I want the appropriate views to handle it. Thanks!

Upvotes: 0

Views: 957

Answers (1)

Derek Beattie
Derek Beattie

Reputation: 9478

You could use a messenger of some sort, like mvvm light's messenger. The View can listen for an error message and then display a notification sent by the VM.

See an example here.

Upvotes: 1

Related Questions