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,請參考 「格式化或顯示資料值轉換 」,裡面有更多撰寫自己數值轉換器的程式碼範例。 這個主題也討論了如何將 ConverterParameter 屬性與 C++ 字串格式化函式一起使用。
<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 來報告未實作的例外。 只有當你用轉換器做雙向綁定,或用 XAML 做序列化時,才需要在轉換器裡加 ConvertBack 方法。
UnsetValue 應從提供資料綁定轉換為相依屬性的 IValueConverter 實作回傳,適用於轉換器無法轉換來源值的情況。 轉換器不應該在 Convert 裡拋出例外;這些例外會以執行時例外的形式出現,你需要在 UnhandledException 中新增處理,甚至更糟的是,使用者會看到它們是真正的執行時例外。 轉換器實作應遵循一般綁定模式,即任何失敗綁定都不做任何事,也不會提供值,而 UnsetValue 而非 null 是綁定引擎能理解的哨兵值。 如需詳細資訊,請參閱 深入數據綁定。
Note
若要與以 C++ 撰寫的自訂值轉換器進行資料綁定,必須直接或間接包含定義 IValueConverter 實作類別的標頭檔案,並包含在其中一個程式碼背後的檔案中。
移轉注意事項
在 Windows 執行階段 中,IValueConverter 方法的語言參數使用字串,而非像 Windows Presentation Foundation(WPF)介面定義中那樣使用 CultureInfo 物件。
方法
| 名稱 | Description |
|---|---|
| Convert(Object, TypeName, Object, String) |
在將原始資料傳送給目標物件以顯示於使用者介面前,先修改來源資料。 |
| ConvertBack(Object, TypeName, Object, String) |
在將目標資料傳遞給來源物件前先修改。 此方法僅在 雙向 綁定中被呼叫。 |