Sunday, 1 February 2009

Validation in MVVM

We're following the MVVM pattern and using Josh Smith's example app Using a Viewmodel to provide meaningful Validation Error Messages to implement validation.

When I was in debugger I noticed that some code was executing twice so I traced through the code once the focus left the textbox.

The order of processing was:
[External Code]
ViewModel.Property.Set
OnPropertyChanged
[External Code]
ViewModel.this[propertyName]
But when you add in a FormattingConverter the order becomes:
[External Code]
FormattingConverter.ConvertBack
[External Code]
ViewModel.Property.Set
OnPropertyChanged
[External Code]
ViewModel.Property.Get
[External Code]
FormattingConverter.Convert
[External Code]
ViewModel.this[propertyName]
[External Code]
ViewModel.this[propertyName]
Which means that the validation gets fired twice.

Because we don't want invalid data in our Model we've recently moved the setting of the Model.Property into the ModelView.this[propertyName] method - not ideal but it is the last opportunity where we still have control. Of course the "double-validation" results in the Model.Property being set twice. Not usually a problem but I fear some hidden side-effect somewhere down the line.

Another slight aggravation is that the Convert function is called before the validation and therefore invalid data will fail to convert then we'll attempt the conversion in the validation process (which was the whole point of this exercise).

No comments: