Overview
As we all know, in a asp.net application, we can use validation controls to validate data entry, and unfortunately there is no validation control provided in Silverlight, but Silverlight provides some basic data validation support for two-way data binding. We can define validation rules in the set set, throw exceptions to illegal data, and finally validate data by capturing validation error events.
This article describes how data validation is done in Silverlight applications.
Prepare knowledge
Validation errors are triggered in the following two scenarios in Silverlight:
1. Throw an exception when performing data transformations in the binding engine
2. Throw an exception in the set set of the business entity
To be able to receive notifications in the case of validation errors, we must set the following two properties to true on the bound object:
Validatesonexceptions: Tells the binding engine to create a validation exception when an exception occurs
NotifyOnValidationError: Tells the binding engine to trigger the Bindingvalidationerror event when there are validation errors or error exclusions
Both of these properties are defined in the binding class, as shown in the following code:
The Bindingvalidationerror event is defined in FrameworkElement, which allows you to receive parameters of the Validationerroreventargs type. A very important property Action is defined in Validationerroreventargs, which is defined as follows:
Here added represents a new validation exception, removed indicates that a validation exception has been excluded. Let's take a look at how we can use them to validate data in the following example.