Oct 162012

UPDATE: due to many requests, I have compiled the code below into a project that you can download from here: Validation.zip

To my big surprise the Microsoft team behind the WinRT XAML framework has decided not to include the built-in support for validation that exists in the WPF and Silverlight frameworks. Anyway, for anyone that needs an alternative, I have created a set of helper classes to make things easier.

Shout it

The Validation static class contains two attached properties which work together for making the validation engine work:

  • Validation.Property contains the name of the bound property for which validation is done
  • Validation.ValidationPlaceholder contains a reference to a ContentControl which will be used for displaying any validation errors
  • The second part involved in the validation process is the implementation of the INotifyDataErrorInfo interface. I am providing here a ViewModel base class that contains both an implementation of the INotifyPropertyChanged and an implementation of INotifyDataErrorInfo which relies on the attributes available in the System.ComponentModel.DataAnnotations namespace for performing validation on the members:

    I have created a custom control that is used for displaying the validation errors. This control has nothing special, it just inherits from ContentControl and uses an ItemsControl for showing all validation errors belonging to a certain property:

    Finally, here is a very simple ViewModel and the associated XAML for it, which use the above framework. The sample code assumes that the DataContext of the XAML snippet is set to an instance of the SampleViewModel: