Share via


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 を実装することは非常に一般的です。 コンバーターに ConvertBack メソッドが必要なのは、双方向バインディングにコンバーターを使用している場合、またはシリアル化に XAML を使用している場合のみです。

コンバーターがソース値を変換できない場合は、依存関係プロパティへのデータ バインディングでの変換を提供する IValueConverter 実装から UnsetValue を返す必要があります。 コンバーターは、 Convert でその場合の例外をスローしないでください。これらは、 UnhandledException で処理を追加する必要がある実行時例外として表示されます。さらに悪いことに、ユーザーには実際の実行時例外として表示されます。 コンバーターの実装は、失敗したバインディングは何も行わず、値を提供しないという一般的なバインディング パターンに従う必要があります。また、null ではなく UnsetValue は、バインディング エンジンが認識するその場合の sentinel 値です。 詳しくは、「データ バインディングの詳細」をご覧ください。

注意

Visual C++ コンポーネント拡張機能 (C++/CX) で記述されたカスタム値コンバーターにデータ バインドするには、IValueConverter 実装クラスが定義されているヘッダー ファイルを、分離コード ファイルの 1 つに直接または間接的に含める必要があります。 詳細については、「 C++ を使用して初めて作成する」を参照してください。

ヒント

UWP アプリの既定のプロジェクト テンプレートには、ヘルパー クラス BooleanToVisibilityConverter が含まれています。 このクラスは、コントロール ロジック クラスのブール値を使用して XAML コントロール テンプレートの Visibility 値を設定する一般的なカスタム コントロール シナリオを処理する IValueConverter 実装です。

移行に関する注意事項

Windows ランタイムでは、IValueConverter メソッドの言語パラメーターでは、インターフェイスの Windows Presentation Foundation (WPF) および Microsoft Silverlight 定義と同様に CultureInfo オブジェクトを使用するのではなく、文字列を使用します。

メソッド

Convert(Object, TypeName, Object, String)

UI に表示するために、ソース データをターゲットに渡す前に変更します。

ConvertBack(Object, TypeName, Object, String)

ターゲット データをソース オブジェクトに渡す前に変更します。 このメソッドは、 TwoWay バインドでのみ呼び出されます。

適用対象

こちらもご覧ください