共用方式為


HOW TO:對自訂物件實作驗證邏輯

本範例示範如何對自訂物件實作驗證邏輯,然後再繫結到該物件。

範例

如果來源物件實作 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。

請參閱

工作

HOW TO:實作繫結驗證

參考

ExceptionValidationRule

其他資源

資料繫結 HOW TO 主題