WPF Commanding and Data Annotations Validation

I recently ran into the need to create a simple WPF app with a data form front end and which should provide some simple validation feedback to the user. I thought this would be pretty straightforward using the WPF commanding support and Data Annotations to provide some simple validation metadata. I wanted to use an M-V-VM approach so that I could unit test my View Model code. This is a screenshot of the prototype app:

The save button should remain disabled until the fields have all been entered correctly and also some feedback should be available to the user about which field is preventing the validation as below.

The main method here is CanExecuteSave since this will determine when my save button is enabled/disabled. So, in order for this method to return true I must have fully valid data. Although there are a few variations in how you approach validation in WPF it felt natural to me to try out using Data Annotations since I have used these for validation in Asp.Net MVC applications. These work by marking the data properties with attributes which are defined in the System.ComponentModel.DataAnnotations namespace. So, I just added a reference to this assembly and marked up my view model’s properties, like this:

Now, with the metadata in place my CanExecuteSave method can be implemented by reflecting over the attributes and calling the IsValid method on each one. This is achieved by calling the following method:

The ExceptionvalidationRule sets up the validation to respond to exceptions thrown in the property setter. Note, I had previously experimented with custom ValidationRule derived classes to provide the validation but I never got this to work as well for my scenario.

it just remains to define the textBoxStyle used as the style can be used to control the visual feedback given to the user:

Post navigation

4 thoughts on “WPF Commanding and Data Annotations Validation”

I’m fairly new to MVVM, but I’m making great progress. Nice article, but I was wondering how you would provide validation for Entities defined in an Entity Model. I have an SQL backend with an Entity Model based on that and several fields of different types. I’d like to provide validation from the Entities to the UI.

Good post, but I’m concerned about performance when binding to a large collection of objects, for example in a DataGrid. Validation should be as fast as possible.
I’ve got 2 suggestions:
1. Avoid using exceptions for validation (they are slow) – consider implementing IDataErrorInfo instead.
2. Cache property descriptors per type (reflection is very slow)