WPF Validation using Validation Application Block Part 2 – Client side
This is second part of my article where I talk about Validation in WPF using Entlib Validation Application Block. First part of my article is located on this location : https://www.radenkozec.com/post/2009/07/07/WPF-Validation-using-Validation-Application-Block-41-Part-1-e28093-Server-side/
There are many articles about client side validation in WPF. Most of these articles are similar and use implementation of IDataErrorInfo interface on Model class.
I have use some methods already described in other articles just to show you how easy it is to implement client side validation in WPF using VAB.
I have model class called Customer where I have implemented IDataErrorInfo. Code looks like this :
public string Error { get { StringBuilder error = new StringBuilder(); ValidationResults results = Validation.ValidateFromAttributes<Customer>(this); foreach (ValidationResult result in results) { error.AppendLine(result.Message); } return error.ToString() ; } } public string this[string columnName] { get { ValidationResults results = Validation.ValidateFromAttributes<Customer>(this); foreach (ValidationResult result in results) { if (result.Key == columnName) { return result.Message; } } return string.Empty; } }
I have called ValidateFromAttributes method of Validation class that exists in VAB to get collection of ValidationResults. It is easy as that.
In Application.Resources of my WPF application I have defined some textbox error template and style to use when validation error is occurred. For this I have borrowed some code from other articles to save on time writing templates and styles.
And final in xaml on textboxes I have added following code where I have turn on Validation and defined witch error template to use :
<TextBox x:Name="txtFirstName" Grid.Column="1" TextWrapping="Wrap" Text="{Binding FirstName, ValidatesOnDataErrors=True}" Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}" />
References :
http://msdn.microsoft.com/en-us/magazine/cc700358.aspx