Share via


방법: 사용자 지정 개체의 유효성 검사 논리 구현

업데이트: 2007년 11월

이 예제에서는 사용자 지정 개체에서 유효성 검사 논리를 구현하고 바인딩하는 방법을 보여 줍니다.

예제

다음 예제에서처럼 소스 개체에서 IDataErrorInfo를 구현하는 경우 비즈니스 계층에 유효성 검사 논리를 제공할 수 있습니다.

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

다음 예제에서 텍스트 상자의 텍스트 속성은 x:Keydata가 지정된 리소스 선언을 통해 바인딩할 수 있게 된 Person 개체의 Age 속성에 바인딩됩니다. DataErrorValidationRuleIDataErrorInfo 구현에서 발생하는 유효성 검사 오류를 검사합니다.

<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

기타 리소스

데이터 바인딩 샘플

데이터 바인딩 방법 항목