방법: 바인딩된 데이터 변환

이 예제는 바인딩에 사용되는 데이터에 변환을 적용하는 방법을 보여 줍니다.

바인딩하는 동안 데이터를 변환하려면 ConvertConvertBack 메서드를 포함하는 IValueConverter 인터페이스를 구현하는 클래스를 만들어야 합니다.

예제

다음 예제는 년, 월, 일만 표시되도록 전달된 날짜 값을 변환하는 날짜 변환기의 구현을 보여 줍니다. IValueConverter 인터페이스를 구현할 때 다음 예제처럼 ValueConversionAttribute 특성으로 구현을 데코레이트하여 변환에 관련된 데이터 형식을 개발 도구에 표시하는 것이 좋습니다.

[ValueConversion(typeof(DateTime), typeof(String))]
public class DateConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        DateTime date = (DateTime)value;
        return date.ToShortDateString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string strValue = value as string;
        DateTime resultDateTime;
        if (DateTime.TryParse(strValue, out resultDateTime))
        {
            return resultDateTime;
        }
        return DependencyProperty.UnsetValue;
    }
}
Public Class DateConverter
    Implements System.Windows.Data.IValueConverter

    Public Function Convert(ByVal value As Object,
                            ByVal targetType As System.Type,
                            ByVal parameter As Object,
                            ByVal culture As System.Globalization.CultureInfo) _
             As Object Implements System.Windows.Data.IValueConverter.Convert

        Dim DateValue As DateTime = CType(value, DateTime)
        Return DateValue.ToShortDateString

    End Function

    Public Function ConvertBack(ByVal value As Object,
                                ByVal targetType As System.Type,
                                ByVal parameter As Object,
                                ByVal culture As System.Globalization.CultureInfo) _
            As Object Implements System.Windows.Data.IValueConverter.ConvertBack

        Dim strValue As String = value
        Dim resultDateTime As DateTime
        If DateTime.TryParse(strValue, resultDateTime) Then
            Return resultDateTime
        End If
        Return DependencyProperty.UnsetValue

    End Function
End Class

변환기를 만든 후 XAML(Extensible Application Markup Language) 파일에 리소스로 추가할 수 있습니다. 다음 예제에서 srcDateConverter가 정의된 네임스페이스에 매핑됩니다.

<src:DateConverter x:Key="dateConverter"/>

마지막으로 다음 구문을 사용하여 바인딩에서 변환기를 사용할 수 있습니다. 다음 예제에서 TextBlock의 텍스트 콘텐츠는 외부 데이터 원본의 속성인 StartDate에 바인딩됩니다.

<TextBlock Grid.Row="2" Grid.Column="0" Margin="0,0,8,0"
           Name="startDateTitle"
           Style="{StaticResource smallTitleStyle}">Start Date:</TextBlock>
<TextBlock Name="StartDateDTKey" Grid.Row="2" Grid.Column="1" 
    Text="{Binding Path=StartDate, Converter={StaticResource dateConverter}}" 
    Style="{StaticResource textStyleTextBlock}"/>

위의 예제에서 참조된 스타일 리소스는 이 항목에 나오지 않은 리소스 섹션에 정의되어 있습니다.

참고 항목