IValueConverter.Convert(Object, TypeName, Object, String) 메서드

정의

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

public:
 Platform::Object ^ Convert(Platform::Object ^ value, TypeName targetType, Platform::Object ^ parameter, Platform::String ^ language);
IInspectable Convert(IInspectable const& value, TypeName const& targetType, IInspectable const& parameter, winrt::hstring const& language);
public object Convert(object value, System.Type targetType, object parameter, string language);
function convert(value, targetType, parameter, language)
Public Function Convert (value As Object, targetType As Type, parameter As Object, language As String) As Object

매개 변수

value
Object

Platform::Object

IInspectable

대상에 전달되는 원본 데이터입니다.

targetType
TypeName Type

대상 속성의 형식(Microsoft .NET용 System.Type , C++/CX 및 C++/WinRT용 TypeName 도우미 구조체)입니다.

parameter
Object

Platform::Object

IInspectable

변환기 논리에 사용할 선택적 매개 변수입니다.

language
String

Platform::String

winrt::hstring

변환의 언어입니다.

반환

Object

Platform::Object

IInspectable

대상 종속성 속성에 전달할 값입니다.

예제

다음 예제에서는 매개 변수언어 매개 변수를 사용하여 Convert 메서드를 구현하는 방법을 보여 있습니다.

//
// 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();
        }
    }
}
Imports System.Collections.ObjectModel
Imports System.Windows.Data
Imports System.Globalization

Partial Public Class Page
    Inherits UserControl

    Public MyMusic As New ObservableCollection(Of Recording)()
    Public Sub New()
        InitializeComponent()

        ' Add items to the collection.
        MyMusic.Add(New Recording("Sheryl Crow", "Detours", New DateTime(2008, 2, 5)))
        MyMusic.Add(New Recording("Brandi Carlisle", "The Story", New DateTime(2007, 4, 3)))
        MyMusic.Add(New Recording("Patty Griffin", "Children Running Through", New DateTime(2007, 2, 6)))

        ' Set the data context for the combo box.
        MusicCombo.DataContext = MyMusic
    End Sub
End Class

' Simple business object. 
Public Class Recording
    Public Sub New()
    End Sub
    Public Sub New(ByVal artistName As String, ByVal cdName As String, _
       ByVal release As DateTime)
        Artist = artistName
        Name = cdName
        ReleaseDate = release
    End Sub
    Private artistValue As String
    Private nameValue As String
    Private releaseDateValue As DateTime
    Public Property Artist() As String
        Get
            Return artistValue
        End Get
        Set(ByVal value As String)
            artistValue = value
        End Set
    End Property
    Public Property Name() As String
        Get
            Return nameValue
        End Get
        Set(ByVal value As String)
            nameValue = value
        End Set
    End Property
    Public Property ReleaseDate() As DateTime
        Get
            Return releaseDateValue
        End Get
        Set(ByVal value As DateTime)
            releaseDateValue = value
        End Set
    End Property
End Class

Public Class DateFormatter
    Implements IValueConverter

    ' This converts the DateTime object to the string to display. 
    Public Function Convert(ByVal value As Object, ByVal targetType As Type, _
        ByVal parameter As Object, ByVal language As System.String) As Object _
        Implements IValueConverter.Convert

        ' Retrieve the format string and use it to format the value. 
        Dim formatString As String = TryCast(parameter, String)
        If Not String.IsNullOrEmpty(formatString) Then

            Return String.Format(New CultureInfo(language), formatString, value)
        End If

        ' If the format string is null or empty, simply call ToString() 
        ' on the value. 
        Return value.ToString()
    End Function

    ' No need to implement converting back on a one-way binding.
    Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, _
        ByVal parameter As Object, _
        ByVal language As System.String) As Object _
        Implements IValueConverter.ConvertBack
        Throw New NotImplementedException()
    End Function
End Class

설명

Convert 메서드의 targetType 매개 변수는 Microsoft .NET 또는 C++로 프로그래밍하는지 여부에 따라 형식 시스템 정보를 보고하는 다양한 기술을 사용합니다.

  • Microsoft .NET의 경우 이 매개 변수는 System.Type 형식의 instance 전달합니다.
  • C++/CX 및 C++/WinRT의 경우 이 매개 변수는 TypeName 구조체 값을 전달합니다. TypeName::Kind 에는 Microsoft와 유사한 형식의 간단한 문자열 이름이 포함되어 있습니다. NET의 입니다 Type.Name. 바인딩 엔진에서 변환기를 호출하면 대상 종속성 속성의 속성 형식을 조회하여 targetType 값이 전달됩니다. 다음 두 가지 이유 중 하나로 Convert 구현에서 이 값을 사용할 수 있습니다.
  • 변환기는 항상 특정 형식의 개체를 반환할 것으로 예상하며 변환기가 호출되는 바인딩이 변환기를 올바르게 사용하는지 확인하려고 합니다. 그렇지 않은 경우 대체 값을 반환하거나 예외를 throw할 수 있습니다(아래 "변환기에서 예외"참조).
  • 변환기는 둘 이상의 형식을 반환할 수 있으며, 변환기에서 반환해야 하는 형식을 알려 줍니다. 예를 들어 동일한 변환기 코드 내에서 개체-개체 변환 및 개체-문자열 변환을 구현할 수 있습니다.

언어 는 시스템 값이 아닌 특정 바인딩의 ConverterLanguage 값에서 제공되므로 빈 문자열일 수 있습니다.

매개 변수 는 특정 바인딩의 ConverterParameter 값에서 제공되며 기본적으로 null 입니다. 변환기에서 매개 변수를 사용하여 반환되는 내용을 수정하는 경우 일반적으로 바인딩에서 전달되고 변환기가 처리하는 항목의 유효성을 검사하기 위한 몇 가지 규칙이 필요합니다. 일반적인 규칙은 변환기에서 서로 다른 반환 값을 생성하는 이름 모드인 문자열을 전달하는 것입니다. 예를 들어 서로 다른 UI 컨트롤 형식 및 레이아웃에 각각 적합한 서로 다른 길이 문자열을 반환하는 "단순" 및 "자세한 정보 표시" 모드가 있을 수 있습니다.

변환기에서 예외

데이터 바인딩 엔진에서 사용자가 제공한 변환기에서 throw 된 예외를 catch 하지 않습니다. Convert 메서드에 의해 throw되는 예외 또는 Convert 메서드가 호출하는 메서드에서 throw된 예외는 런타임 오류로 처리됩니다. 변환 오류가 발생하더라도 바인딩이 대체를 사용하거나 적절한 결과를 표시할 수 있는 상황에서 변환기를 사용하는 경우 변환기가 DependencyProperty.UnsetValue 를 반환하고 예외를 throw하지 않도록 하는 것이 좋습니다. DependencyProperty.UnsetValue 는 종속성 속성 시스템에 특별한 의미가 있는 sentinel 값이며, 이 값이 전달되는 바인딩은 FallbackValue를 사용합니다.

예외를 throw하는 또 다른 대안은 원래 값을 변경하지 않고 반환하고 바인딩 instance 해당 값으로 수행할 수 있는 작업을 처리하도록 하는 것입니다. 대부분의 경우 실패하는 UI 바인딩은 오류 사례가 아닙니다. 원본 값을 사용하지 않고 대신 DependencyProperty.UnsetValue 를 사용하여 아무것도 표시하지 않거나 대체를 사용합니다.

에 대한 작업을 기반으로 try/catch는 Convert 메서드의 일반적인 구현 패턴이지만 위에서 언급한 이유로 다시 시도해서는 안 됩니다.

매개 변수언어 매개 변수를 사용하여 Convert 메서드를 구현하는 방법을 보여 주는 예제는 IValueConverter 인터페이스를 참조하세요.

적용 대상

추가 정보