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

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

예제

다음 예제와 같이 원본 개체가 IDataErrorInfo를 구현하는 경우 비즈니스 계층에 유효성 검사 논리를 제공할 수 있습니다. 이 예제에서는 IDataErrorInfo를 구현하는 Person 개체를 정의합니다.

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

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

<Window x:Class="BusinessLayerValidation.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WPF IDataErrorInfo Sample" Width="350" Height="150"
        xmlns:src="clr-namespace:BusinessLayerValidation">
    
    <Window.Resources>
        <src:Person x:Key="data"/>

        <!--The tool tip for the TextBox to display the validation error message.-->
        <Style x:Key="textBoxInError" TargetType="TextBox">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip"
                            Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                        Path=(Validation.Errors)[0].ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>

    <StackPanel Margin="20">
        <TextBlock>Enter your age:</TextBlock>

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

        <TextBlock>Mouse-over to see the validation error message.</TextBlock>
    </StackPanel>
</Window>

또는 DataErrorValidationRule을 사용하는 대신 ValidatesOnDataErrors 속성을 true로 설정할 수 있습니다.

참고 항목