Share via


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

型参照としてのターゲット プロパティの型 (System.Type for Microsoft .NET、Visual C++ コンポーネント拡張機能の TypeName ヘルパー構造体 (C++/CX))。

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

注釈

Convert メソッドの targetType パラメーターは、Microsoft .NET または Visual C++ コンポーネント拡張機能 (C++/CX) のどちらを使用してプログラミングしているかに応じて、システム情報の種類をレポートするさまざまな手法を使用します。

  • Microsoft .NET の場合、このパラメーターは System.Type 型のインスタンスを渡します。
  • Visual C++ コンポーネント拡張機能 (C++/CX) の場合、このパラメーターは TypeName 構造体の値を渡します。 TypeName::Kind には、Microsoft と同様に、型の単純な文字列名が含まれています。NET の Type.Name。 コンバーターがバインド エンジンによって呼び出されると、ターゲット依存関係プロパティのプロパティ型を検索することによって targetType 値が渡されます。 Convert 実装では、次の 2 つの理由のいずれかでこの値を使用できます。
  • コンバーターでは、常に特定の型のオブジェクトが返されることを想定しており、コンバーターが呼び出されるバインディングでコンバーターが正しく使用されていることを確認する必要があります。 そうでない場合は、フォールバック値を返すか、例外をスローする可能性があります (ただし、以下の「コンバーターからの例外」を参照してください)。
  • コンバーターは複数の型を返すことができます。また、 を使用して、返す必要がある型をコンバーターに通知する必要があります。 たとえば、オブジェクトからオブジェクトへの変換と、オブジェクトから文字列への変換を同じコンバーター コード内に実装できます。

language は、システム値ではなく、特定のバインディングの ConverterLanguage 値から取得されるため、空の文字列である可能性があります。

パラメーター は、特定のバインディングの ConverterParameter 値から取得され、既定では null です 。 コンバーターでパラメーターを使用して返される内容を変更する場合は、通常、バインディングによって渡され、コンバーターによって処理される内容を検証するための規則が必要です。 一般的な規則は、コンバーターのモードに名前を付け、結果として異なる戻り値になる文字列を渡すことです。 たとえば、異なる UI コントロールの種類とレイアウトでの表示に適した、それぞれ異なる長さの文字列を返す "Simple" モードと "Verbose" モードがあるとします。

コンバーターからの例外

データ バインディング エンジンは、ユーザー指定のコンバーターによってスローされる例外をキャッチしません。 Convert メソッドによってスローされた例外、または Convert メソッドが呼び出すメソッドによってスローされたキャッチされていない例外は、実行時エラーとして扱われます。 バインディングでフォールバックを使用できる状況でコンバーターを使用している場合、または変換エラーが発生した場合でも適切な結果が表示される場合は、コンバーターが DependencyProperty.UnsetValue を返し、例外をスローしないことを検討してください。 DependencyProperty.UnsetValue は依存関係プロパティ システムで特別な意味を持つ sentinel 値であり、この値を渡されるバインドでは FallbackValue が使用されます。

例外をスローするもう 1 つの方法は、元の を変更せずに返し、バインディング インスタンスがその値で何を行うかを処理できるようにすることです。 ほとんどの場合、失敗した UI バインドはエラー ケースになりません。 ソース値は使用せず、 代わりに DependencyProperty.UnsetValue を使用して何も表示しないか、フォールバックを使用します。

値に何かを行うことに基づいて try/catch は Convert メソッドの一般的な実装パターンですが、上記の理由から、再スローしないでください。

パラメーターと言語パラメーターを使用して Convert メソッドを実装する方法を示す例については、IValueConverter インターフェイスを参照してください。

適用対象

こちらもご覧ください