Expand Minimize

How to: Implement Validation Logic on Custom Objects

This example shows how to implement validation logic on a custom object and then bind to it.

You can provide validation logic on the business layer if your source object implements IDataErrorInfo, as in the following example:

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;
        }
    }
}

In the following example, the text property of the text box binds to the Age property of the Person object, which has been made available for binding through a resource declaration that is given the x:Key data. The DataErrorValidationRule checks for the validation errors raised by the IDataErrorInfo implementation.

<TextBox Style="{StaticResource textBoxInError}">
  <TextBox.Text>
    <Binding Path="Age" Source="{StaticResource data}"
             UpdateSourceTrigger="PropertyChanged">
      <Binding.ValidationRules>
        <!--DataErrorValidationRule checks for validation 
            errors raised by the IDataErrorInfo object
            Alternatively, you can set ValidatesOnDataErrors="True"
            on the Binding.-->
        <DataErrorValidationRule/>
      </Binding.ValidationRules>
    </Binding>
  </TextBox.Text>
</TextBox>

Alternatively, instead of using the DataErrorValidationRule, you can set the ValidatesOnDataErrors property to true.

For the complete sample, see Business Layer Validation Sample.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft