WPF Validation
(This page is a work in progress)
As the primary Microsoft platform for building client applications, Windows Presentation Foundation has a rich validation system. This article is going to look at the approaches that WPF enables for validation, how to style validation messages to suit your needs, as well as some of the limitations of the system. This article is targeted at .NET 3.5 SP1.
How to Validate
WPF allows you to declare validation logic in the following places:
- You can declare a rule in XAML and apply it to a binding (UI only)
- You can throw exceptions in property setters (models)
- You can implement the IDataErrorInfo interface (models)
Validation Rules via XAML
WPF allows your rules to be encapsulated within a class, and to have the rule applied via XAML. You begin by defining a rule:
Code sample goes here
Your rule can then be applied by using object element syntax to declare your binding:
XAML code goes here
This will be enough to have error messages appear on screen:
Screenshot goes here
We will talk more about what you can do with validation rules later.
Throwing Exceptions in Setters
An easy way to perform validation in models is to throw an exception in the setters of your properties:
Code sample goes here
When you declare a binding, you can either use object element syntax, as per below:
XAML syntax
Or make use of a handy property that was introduced in .NET 3.5:
XAML syntax (shorter)
This approach is useful because it allows you to consolidate validation logic in your models, but it has a few drawbacks which we'll discuss later. A better approach to model validation is the IDataErrorInfo
interface.
Implementing IDataErrorInfo
WPF in .NET 3.5 introduced IDataErrorInfo
support out of the box. The implementation is quite simple:
Code sample goes here
As with model binding, you can either use object element syntax:
XAML sample here
Or a handy attribute that was introduced in .NET 3.5:
XAML sample (shorter)
How to display validation results
WPF makes it easy to display validation errors against a UI element.