IValueConverter インターフェイス
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
バインディング エンジンを通過するデータの変更を許可するメソッドを公開します。
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 インターフェイスを実装し、オブジェクトのコレクションへのデータ バインディング時にコンバーターを使用する方法を示しています。
Note
C++/WinRT を使用している場合は、独自の値コンバーターを作成するコード例については、表示用のデータ値の書式設定または変換に関するページを参照してください。 このトピックでは、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 に色名を付けて表示することができます。 Convert と ConvertBack を実装することで、バインド エンジンによってターゲットとソースの間で渡されるデータ値の形式を変更できます。 関数型実装では常に Convert を実装する必要がありますが、実装されていない例外を報告するように ConvertBack を実装することは非常に一般的です。 コンバーターで ConvertBack メソッドが必要なのは、双方向バインディングにコンバーターを使用している場合、またはシリアル化に XAML を使用している場合のみです。
コンバーターがソース値を変換できない場合は、依存関係プロパティへのデータ バインディングでの変換を提供する IValueConverter 実装から UnsetValue を返す必要があります。 コンバーターは、 Convert でその場合の例外をスローしないでください。これらは、 UnhandledException で処理を追加する必要がある実行時例外として表示されます。さらに悪いことに、ユーザーには実際の実行時例外として表示されます。 コンバーターの実装は、失敗したバインディングが何も行わず値を提供しない一般的なバインド パターンに従う必要があります。Null ではなく UnsetValue は、バインディング エンジンが認識するその場合のセンチネル値です。 詳細については、「データ バインディングの詳細」を参照してください。
Note
C++ で記述されたカスタム値コンバーターにデータ バインドするには、IValueConverter 実装クラスが定義されているヘッダー ファイルを、分離コード ファイルの 1 つに直接または間接的に含める必要があります。
移行のメモ
Windows ランタイムでは、IValueConverter メソッドの言語パラメーターでは、インターフェイスのWindows Presentation Foundation (WPF) 定義と同様に CultureInfo オブジェクトを使用するのではなく、文字列を使用します。
メソッド
| 名前 | 説明 |
|---|---|
| Convert(Object, TypeName, Object, String) |
UI に表示するために、ソース データをターゲットに渡す前に変更します。 |
| ConvertBack(Object, TypeName, Object, String) |
ソース オブジェクトに渡す前に、ターゲット データを変更します。 このメソッドは、 TwoWay バインドでのみ呼び出されます。 |