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 相當常見,以便報告未實作的例外狀況。 如果您使用轉換子進行雙向系結,或使用 XAML 進行序列化,則只需要轉換子中的 ConvertBack 方法。

在轉換程式無法轉換來源值的情況下,應該從 IValueConverter 實作傳回UnsetValue,此實作會在資料系結中提供相依性屬性的轉換。 轉換程式不應該在 Convert中擲回該案例的例外狀況;這些會呈現為執行時間例外狀況,而您需要在 UnhandledException 中新增處理,或更糟的使用者顯示為實際的執行時間例外狀況。 轉換子實作應該遵循一般系結模式,讓任何失敗的系結不會執行任何動作,而且未提供值, 而 UnsetValue 而非 null 是系結引擎瞭解的該案例的 sentinel 值。 如需詳細資訊,請參閱深入了解資料繫結

注意

若要將資料系結至以 Visual C++ 元件延伸模組撰寫的自訂值轉換器, (C++/CX) ,必須在其中一個程式碼後置檔案中包含 IValueConverter 實作類別的標頭檔。 如需詳細資訊,請參閱 使用 C++ 建立您的第一個

提示

UWP app 的一些預設專案範本包含協助程式類別 BooleanToVisibilityConverter。 這個類別是 IValueConverter 實作,可處理常見的自訂控制項案例,其中您會使用控制項邏輯類別中的布林值來設定 XAML 控制項範本中的 Visibility 值。

移轉注意事項

在Windows 執行階段中,IValueConverter 方法的語言參數會使用字串,而不是在介面的 Windows Presentation Foundation (WPF) 和 Microsoft Silverlight 定義中使用CultureInfo物件。

方法

Convert(Object, TypeName, Object, String)

先修改來源資料,再將它傳遞至目標,以在 UI 中顯示。

ConvertBack(Object, TypeName, Object, String)

先修改目標資料,再將它傳遞至來源物件。 這個方法只會在 TwoWay 系結中呼叫。

適用於

另請參閱