Практическое руководство. Реализация проверки для пользовательских объектов

В этом примере демонстрируется реализация проверки для пользовательского объекта и последующей привязки к нему.

Пример

Можно обеспечить проверку для бизнес-слоя, если источник объекта реализует 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;
        }
    }
}

В следующем примере свойство Text текстового поля привязывается к свойству Age объекта Person, который был сделан доступным для привязки через объявление ресурса, предоставляемое 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

Другие ресурсы

Практические руководства по привязке данных