语言

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,请参阅 格式设置或转换数据值以显示 更多代码示例,以创作自己的值转换器。 本主题还讨论了如何将 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 方法。

在转换器无法转换源值的情况下,应从 IValueConverter 实现返回 UnsetValue,该实现在数据绑定中提供到依赖属性的转换。 转换器不应在 Convert 中引发该情况的异常;这些异常将显示为运行时异常,你需要在 UnhandledException 中添加处理,或者更糟,但用户似乎显示为实际的运行时异常。 转换器实现应遵循一般绑定模式,即任何失败的绑定不执行任何操作且不提供值, UnsetValue 而不是 null 是绑定引擎理解的该情况的 sentinel 值。 有关详细信息,请参阅深入了解数据绑定。

注释

若要将数据绑定到使用 C++ 编写的自定义值转换器,必须在其中一个代码隐藏文件中包括 IValueConverter 实现类的头文件(直接或间接包含)。

迁移说明

在Windows 运行时中,IValueConverter 方法的语言参数使用字符串,而不是像在接口的 Windows Presentation Foundation (WPF) 定义中那样使用 CultureInfo 对象。

方法

名称 说明
Convert(Object, TypeName, Object, String)

在将源数据传递给目标以在 UI 中显示之前对其进行修改。

ConvertBack(Object, TypeName, Object, String)

在将目标数据传递给源对象之前修改目标数据。 此方法仅在 TwoWay 绑定中调用。

适用于

另请参阅