如何:在自定义对象上实现验证逻辑

本示例演示如何针对自定义对象实现验证逻辑,然后绑定到该对象。

示例

如果源对象实现了 IDataErrorInfo,则可以在业务层提供验证逻辑,如下例所示:

    Public Class Person
        Implements IDataErrorInfo

        Private _age As Integer
        Public Property Age() As Integer
            Get
                Return _age
            End Get
            Set(ByVal value As Integer)
                _age = value
            End Set
        End Property

        Public ReadOnly Property [Error]() As String Implements IDataErrorInfo.Error
            Get
                Return Nothing
            End Get
        End Property

        Default Public ReadOnly Property Item(ByVal columnName As String) As String Implements IDataErrorInfo.Item
            Get
                Dim result As String = Nothing

                If columnName = "Age" Then
                    If Me._age < 0 OrElse Me._age > 150 Then
                        result = "Age must not be less than 0 or greater than 150."
                    End If
                End If
                Return result
            End Get
        End Property
    End Class
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;
        }
    }
}

在下面的示例中,文本框的文本属性绑定到 Person 对象的 Age 属性,通过 x:Key data 提供的资源声明,该属性已可用于绑定。 DataErrorValidationRule 检查 IDataErrorInfo 实现所引发的验证错误。

<TextBox Style="{StaticResource textBoxInError}">
    <TextBox.Text>
        <!--By setting ValidatesOnExceptions to True, it checks for exceptions
        that are thrown during the update of the source property.
        An alternative syntax is to add <ExceptionValidationRule/> within
        the <Binding.ValidationRules> section.-->
        <Binding Path="Age" Source="{StaticResource data}"
                 ValidatesOnExceptions="True"
                 UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <!--DataErrorValidationRule checks for validation 
                    errors raised by the IDataErrorInfo object.-->
                <!--Alternatively, you can set ValidationOnDataErrors="True" on the Binding.-->
                <DataErrorValidationRule/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

如果不使用 DataErrorValidationRule,则可以将 ValidatesOnDataErrors 属性设置为 true。

请参见

任务

如何:实现绑定验证

参考

ExceptionValidationRule

其他资源

数据绑定帮助主题