4

I am developing a WPF application using the MVVM pattern as described by Josh Smith in the article at http://msdn.microsoft.com/en-us/magazine/dd419663.aspx.

I can't figure out a good way of reacting to Convert Back errors (for example when a user types a letter in a textbox bound to a double).

Josh Smith proposes a Validation system where the Model validates it's own values and presents the boolean result through SomeModel.IsValid. Josh then uses the value of IsValid as predicate for certain buttons, e.g. a Save button on a form - if the form has not been validly completed, IsValid is false and the Save button is disabled.

This method works really well. However, when a user types a value in a textbox that cannot be converted, a ConvertBack error occurs. The ViewModel's setter for the property is never called, and thus the Model's property is never updated. IsValid remains true. Although the View responds to the Validation error by showing an error message and highlighting the error (or whatever the setting may be), the Save button remains active, as the IsValid property of the Model is still true, as the Model has not been updated.

Are there any MVVM users who have experienced this same challenge? Any ideas?

One suggestion is that the property on the model could be Nullable. Then the Converter should set the source to Null if the user enters non-convertable date (such as a letter in a textbox bound to a double). However, I could not find a simple way of doing this - it seems to require writing custom converters for every data type I require the functionality for, and for every number format I require it in. This is a very poor sollution to what seems like a design challange.

Any ideas?

Pieter Müller
  • 4,573
  • 6
  • 38
  • 54

2 Answers2

1

I have found two excellent articles addressing this issue:

One by Karl Shifflett: http://karlshifflett.wordpress.com/mvvm/input-validation-ui-exceptions-model-validation-errors/

One by Josh Smith:

http://joshsmithonwpf.wordpress.com/2008/11/14/using-a-viewmodel-to-provide-meaningful-validation-error-messages/

It's a bit too complex to duplicate here, so I will just mark the links as answer.

Pieter Müller
  • 4,573
  • 6
  • 38
  • 54
1

You might be interested in the BookLibrary sample application of the WPF Application Framework (WAF). It shows how Parsing or ConvertBack exceptions are handled as validation errors.

Just enter "abc" in the "Pages" TextBox and see how the validation error is shown as tooltip and the Save button is disabled.

jbe
  • 6,976
  • 1
  • 43
  • 34