IValueConverter 인터페이스

정의

바인딩 엔진을 통과할 때 데이터를 수정할 수 있도록 하는 메서드를 노출합니다.

public interface class IValueConverter
/// [Windows.Foundation.Metadata.ContractVersion(Microsoft.UI.Xaml.WinUIContract, 65536)]
/// [Windows.Foundation.Metadata.Guid(2950507519, 4341, 20851, 183, 192, 53, 144, 189, 150, 203, 53)]
struct IValueConverter
[Windows.Foundation.Metadata.ContractVersion(typeof(Microsoft.UI.Xaml.WinUIContract), 65536)]
[Windows.Foundation.Metadata.Guid(2950507519, 4341, 20851, 183, 192, 53, 144, 189, 150, 203, 53)]
public interface IValueConverter
Public Interface IValueConverter
파생
특성

예제

다음 예제에서는 IValueConverter 인터페이스를 구현하고 개체 컬렉션에 데이터를 바인딩할 때 변환기를 사용하는 방법을 보여줍니다.

참고

C++/WinRT(또는 C++/CX)를 사용하는 경우 데이터 값 서식 지정 또는 변환을 참조하여 사용자 고유의 값 변환기를 작성하는 더 많은 코드 예제를 표시합니다. 또한 이 항목에서는 C++ 문자열 서식 함수와 함께 ConverterParameter 특성을 사용하는 방법에 대해서도 설명합니다.

<UserControl x:Class="ConverterParameterEx.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="using:ConverterParameterEx" 
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" >
        <Grid.Resources>
           <local:DateFormatter x:Key="FormatConverter" />
        </Grid.Resources>
        
        <ComboBox Height="60" Width="250" x:Name="MusicCombo" 
            ItemsSource="{Binding}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock FontWeight="Bold" Text="{Binding Path=Name, Mode=OneWay}" />
                        <TextBlock Text="{Binding Path=Artist, Mode=OneWay}" />
                        <TextBlock Text="{Binding Path=ReleaseDate, Mode=OneWay,
                            Converter={StaticResource FormatConverter}, 
                            ConverterParameter=\{0:d\}}" />
                   </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </Grid>
</UserControl>
//
// MainPage.xaml.h
// Declaration of the MainPage class.
// 

#pragma once

#include "MainPage.g.h"

namespace IValueConverterExample
{

    // Simple business object.
    [Windows::UI::Xaml::Data::Bindable]
    public ref class Recording sealed 
    {
    public: 
        Recording (Platform::String^ artistName, Platform::String^ cdName, Windows::Foundation::DateTime release)
        {
            Artist = artistName;
            Name = cdName;
            ReleaseDate = release;
        }
        property Platform::String^ Artist;
        property Platform::String^ Name;
        property Windows::Foundation::DateTime ReleaseDate;
    };

    public ref class DateFormatter  sealed : Windows::UI::Xaml::Data::IValueConverter 
    {
        // This converts the DateTime object to the Platform::String^ to display.
    public:
        virtual Platform::Object^ Convert(Platform::Object^ value, Windows::UI::Xaml::Interop::TypeName targetType, 
            Platform::Object^ parameter, Platform::String^ language)
        {
            Windows::Foundation::DateTime dt = safe_cast<Windows::Foundation::DateTime>(value); 
            Windows::Globalization::DateTimeFormatting::DateTimeFormatter^ dtf =
                Windows::Globalization::DateTimeFormatting::DateTimeFormatter::ShortDate;
            return dtf->Format(dt); 
        }

        // No need to implement converting back on a one-way binding 
        virtual Platform::Object^ ConvertBack(Platform::Object^ value, Windows::UI::Xaml::Interop::TypeName targetType, 
            Platform::Object^ parameter, Platform::String^ language)
        {
            throw ref new Platform::NotImplementedException();
        }
    };

    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public ref class MainPage sealed
    {
    public:
        MainPage()
        {	
            m_myMusic = ref new Platform::Collections::Vector<Recording^>();

            // Add items to the collection.

            // You can use a Calendar object to create a Windows::Foundation::DateTime
            auto c = ref new Windows::Globalization::Calendar();
            c->Year = 2008;
            c->Month = 2;
            c->Day = 5;
            m_myMusic->Append(ref new Recording("Chris Sells", "Chris Sells Live",
                c->GetDateTime()));

            c->Year = 2007;
            c->Month = 4;
            c->Day = 3;
            m_myMusic->Append(ref new Recording("Luka Abrus",
                "The Road to Redmond", c->GetDateTime()));
            
            c->Year = 2007;
            c->Month = 2;
            c->Day = 3;
            m_myMusic->Append(ref new Recording("Jim Hance",
                "The Best of Jim Hance", dt));
            InitializeComponent();

            // Set the data context for the combo box.
            MusicCombo->DataContext = m_myMusic;	
        }


    protected:
        virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;

    private:
        Windows::Foundation::Collections::IVector<Recording^>^ m_myMusic;
    };
}
using System;
using System.Collections.ObjectModel;
using System.Globalization;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;

namespace ConverterParameterEx
{
    public partial class Page : UserControl
    {

        public ObservableCollection<Recording> MyMusic =
            new ObservableCollection<Recording>();
        public Page()
        {
            InitializeComponent();

            // Add items to the collection.
            MyMusic.Add(new Recording("Chris Sells", "Chris Sells Live",
                new DateTime(2008, 2, 5)));
            MyMusic.Add(new Recording("Luka Abrus",
                "The Road to Redmond", new DateTime(2007, 4, 3)));
            MyMusic.Add(new Recording("Jim Hance",
                "The Best of Jim Hance", new DateTime(2007, 2, 6)));

            // Set the data context for the combo box.
            MusicCombo.DataContext = MyMusic;
        }
    }

    // Simple business object.
    public class Recording
    {
        public Recording() { }
        public Recording(string artistName, string cdName, DateTime release)
        {
            Artist = artistName;
            Name = cdName;
            ReleaseDate = release;
        }
        public string Artist { get; set; }
        public string Name { get; set; }
        public DateTime ReleaseDate { get; set; }
    }

    public class DateFormatter : IValueConverter
    {
        // This converts the DateTime object to the string to display.
        public object Convert(object value, Type targetType, 
            object parameter, string language)
        {
            // Retrieve the format string and use it to format the value.
            string formatString = parameter as string;
            if (!string.IsNullOrEmpty(formatString))
            {
                return string.Format(
                    new CultureInfo(language), formatString, value);
            }
            // If the format string is null or empty, simply call ToString()
            // on the value.
            return value.ToString();
        }

        // No need to implement converting back on a one-way binding 
        public object ConvertBack(object value, Type targetType, 
            object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}

설명

IValueConverter에서 상속하여 원본과 대상 간에 데이터 형식을 변환할 수 있는 클래스를 만들 수 있습니다. 예를 들어 RGBA 값으로 저장하는 색 목록을 포함하지만 UI에 색 이름으로 표시할 수 있습니다. ConvertConvertBack을 구현하면 바인딩 엔진에서 대상과 원본 간에 전달될 때 데이터 값의 형식을 변경할 수 있습니다. 항상 함수 구현을 사용하여 Convert 를 구현해야 하지만 구현되지 않은 예외를 보고하도록 ConvertBack을 구현하는 것이 일반적입니다. 양방향 바인딩에 변환기를 사용하거나 직렬화에 XAML을 사용하는 경우에만 변환기에서 ConvertBack 메서드가 필요합니다.

변환기가 원본 값을 변환할 수 없는 경우 데이터 바인딩에서 종속성 속성으로 변환을 제공하는 IValueConverter 구현에서 UnsetValue를 반환해야 합니다. 변환기는 변환에서 해당 사례에 대한 예외를 throw해서는 안 됩니다. 이러한 예외는 UnhandledException 에서 처리를 추가해야 하는 런타임 예외로 표시되거나 더 나빠지지만 실제 런타임 예외로 사용자에게 표시됩니다. 변환기 구현은 실패한 바인딩이 아무 작업도 수행하지 않고 값을 제공하지 않는 일반 바인딩 패턴을 따라야 하며, Null이 아닌 UnsetValue는 바인딩 엔진이 이해하는 경우의 sentinel 값입니다. 자세한 내용은 데이터 바인딩 심층 분석을 참조하세요.

참고

Visual C++ 구성 요소 확장(C++/CX)으로 작성된 사용자 지정 값 변환기로 데이터를 바인딩하려면 IValueConverter 구현 클래스가 정의된 헤더 파일을 코드 숨김 파일 중 하나에 직접 또는 간접적으로 포함해야 합니다. 자세한 내용은 C++를 사용하여 첫 번째 만들기를 참조하세요.

UWP 앱의 기본 프로젝트 템플릿 중 일부는 도우미 클래스인 BooleanToVisibilityConverter를 포함합니다. 이 클래스는 컨트롤 논리 클래스의 부울 값을 사용하여 XAML 컨트롤 템플릿에서 Visibility 값을 설정하는 일반적인 사용자 지정 컨트롤 시나리오를 처리하는 IValueConverter 구현입니다.

마이그레이션 정보

Windows 런타임 IValueConverter 메서드의 언어 매개 변수는 WPF(Windows Presentation Foundation) 및 인터페이스의 Microsoft Silverlight 정의에서와 마찬가지로 CultureInfo 개체를 사용하는 대신 문자열을 사용합니다.

메서드

Convert(Object, TypeName, Object, String)

UI에 표시할 대상에 전달하기 전에 원본 데이터를 수정합니다.

ConvertBack(Object, TypeName, Object, String)

대상 데이터를 원본 개체에 전달하기 전에 수정합니다. 이 메서드는 TwoWay 바인딩에서만 호출됩니다.

적용 대상

추가 정보