:Data Validation in 3.5

原文地址:http://blogs.msdn.com/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx

本文讲述了3.5中新增的用IdataErrorInfo来实现数据验证,以及与3.0中通过重载ValidationRule来实现验证的区别和相同点。

Data Validation in 3.5

A cool new feature in the Data area in 3.5 is the support for IDataErrorInfo. Let's take a look at the data validation model in 3.5 by starting with a memory refresher of that in 3.0. We end with a section that discusses how to choose between the different approaches.

3.0 Validation Model

In 3.0, you would create a custom ValidationRule or use the built-in ExceptionValidationRule this way:

                <Binding Source="{StaticResource data}" Path="Age"

                         UpdateSourceTrigger="PropertyChanged">

                    <Binding.ValidationRules>

                        <ExceptionValidationRule/>

                    </Binding.ValidationRules>

                </Binding>

   

If the ExceptionValidationRule has been associated with the binding and there's an exception when the binding engine attempts to set the property on the source, then the binding engine creates a ValidationError with the exception and adds it to the Validation.Errors collection of the bound element. You can use the errors in the collection to provide additional visual feedback (in addition to the default red border for the TextBox in error). You can read more about that in the last section of the Data Binding Overview.

3.5 IDataErrorInfo Support

In 3.5, the data binding engine adds the support for business-layer validation by supporting IDataErrorInfo.  For example, the following Person class implements IDataErrorInfo to specify that the Age of a Person is not valid if it's less than 0 or greater than 150.

     public class Person : IDataErrorInfo

    {

        private int age;

   

        public int Age

        {

            get { return age; }

            set { age = value; }

        }

   

        public string Error

        {

            get

            {

                return null;

            }

        }

   

        public string this[string name]

        {

            get

            {

                string result = null;

   

                if (name == "Age")

                {

                    if (this.age < 0 || this.age > 150)

                    {

                        result = "Age must not be less than 0 or greater than 150.";

                    }

                }

                return result;

            }

        }

    }

   

To use the IDataErrorInfo implementation logic you add the DataErrorValidationRule to the ValidationRules collection, like so:

   

                <Binding Source="{StaticResource data}" Path="Age"

                         UpdateSourceTrigger="PropertyChanged">

                    <Binding.ValidationRules>

                        <DataErrorValidationRule/>

                    </Binding.ValidationRules>

                </Binding>

   

If an error is raised, the binding engine creates a ValidationError with the error and adds it to the Validation.Errors collection of the bound element. The lack of an error clears this validation feedback, unless another rule raises a validation issue.

   

Alternative Syntax

In 3.5, we also provide a "short-hand" for using the DataErrorValidationRule and the ExceptionValidationRule. Instead of adding the DataErrorValidationRule explicitly like in the above snippet, you can set the ValidatesOnDataErrors attribute, like so:

   

                <Binding Source="{StaticResource data}" Path="Age"

                         UpdateSourceTrigger="PropertyChanged"

                         ValidatesOnDataErrors="True"   />

   

The "short-hand" for the ExceptionValidationRule is the ValidatesOnExceptions attribute.  

When to use Validation Rules vs. IDataErrorInfo

Whether you should use a rule that derives from ValidationRule (a custom rule or ExceptionValidationRule) or implement IDataErrorInfo depends on your scenario.

   

The following table and the validation procedure in the next sub-section describe the things you should take into consideration:

  

ValidationRules (custom ValidationRule or ExceptionValidationRule)

IDataErrorInfo

UI or business-layer validation logic

The validation logic is detached from the data source, and can be reused between controls.

The validation logic is closer to the source.

One data source, multiple apps

This is the logical choice if you have one data source that is used by two different apps and you want to validate it differently in each app.

  

WinForms to WPF

  

This is the logical choice if you are porting your app from WinForms to WPF.

   

Validation Procedure

The binding engine follows the following logic during the validation process:

1.       Evaluate all the custom validation rules (but not the ExceptionValidationRule or the DataErrorValidationRule).  If one or more of the custom rules fails, then stop and mark the value as invalid.

2.       Call the setter. If this throws an exception, and if the ExceptionValidationRule was enabled, then stop and mark the value as invalid.

3.       If the DataErrorValidationRule was enabled, check the IDataErrorInfo for the property.  If this indicates an error, then stop and mark the value as invalid.

4.       Mark the value as valid.

   

The attached sample has a TextBox that binds to the Age property of a Person object. The Person class implements IDataErrorInfo, as shown in the earlier snippet.

   

The TextBox binding uses the ExceptionValidationRule to catch exceptions raised during the setter call of the source property, as shown in the following screenshot:

:Data Validation in 3.5

   

The business object layer provides the logic for out-of-range errors (as defined by the IDataErrorInfo implementation):

:Data Validation in 3.5

   

注意的一个问题:

I have a problem with IDataErrorInfo.

In your example, il i set a value like "foo", there is no set call on property Age, exactly what i expected :)

If i set a value like "800", the set is called and my property Age is set to 800, which is typically false. I dont want it..

DataErrorValidationRule informed correctly the User Interface (Red Textbox) but my Object is in fault state..

Is there a solution for DataErrorValidation not call the Set method on my property Age ?

Friday, July 25, 2008 6:14 AM by Mimetis

# re: Data Validation in 3.5

Hi.  Here's the answer about invalid values from the developer.

If you don't want the setter to be called with an invalid value such as 800, you should write your own validation rule and attach it to the binding.   IDataErrorInfo won't help you here – it specifically works with values that have already been set into the Age property.

Thanks,

Carole

Friday, July 25, 2008 3:04 PM by wcsdkteam

说的是当输入800时,Age的set方法还是被调用了,这是不对的,这时就必须用validation rule了。

下载

你可能感兴趣的:(validation)