IValueConverter.Convert(Object, TypeName, Object, String) 方法

定义

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

public:
 Platform::Object ^ Convert(Platform::Object ^ value, TypeName targetType, Platform::Object ^ parameter, Platform::String ^ language);
IInspectable Convert(IInspectable const& value, TypeName const& targetType, IInspectable const& parameter, winrt::hstring const& language);
public object Convert(object value, System.Type targetType, object parameter, string language);
function convert(value, targetType, parameter, language)
Public Function Convert (value As Object, targetType As Type, parameter As Object, language As String) As Object

参数

value
Object

Platform::Object

IInspectable

要传递给目标的源数据。

targetType
TypeName Type

目标属性的类型,作为 Microsoft .NET 的 System.Type (类型引用,是适用于 C++/CX 和 C++/WinRT 的 TypeName 帮助程序结构) 。

parameter
Object

Platform::Object

IInspectable

在转换器逻辑中使用的可选参数。

language
String

Platform::String

winrt::hstring

转换的语言。

返回

Object

Platform::Object

IInspectable

要传递给目标依赖属性的值。

示例

以下示例演示如何使用 参数语言 参数实现 Convert 方法。

//
// 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();
        }
    }
}
Imports System.Collections.ObjectModel
Imports System.Windows.Data
Imports System.Globalization

Partial Public Class Page
    Inherits UserControl

    Public MyMusic As New ObservableCollection(Of Recording)()
    Public Sub New()
        InitializeComponent()

        ' Add items to the collection.
        MyMusic.Add(New Recording("Sheryl Crow", "Detours", New DateTime(2008, 2, 5)))
        MyMusic.Add(New Recording("Brandi Carlisle", "The Story", New DateTime(2007, 4, 3)))
        MyMusic.Add(New Recording("Patty Griffin", "Children Running Through", New DateTime(2007, 2, 6)))

        ' Set the data context for the combo box.
        MusicCombo.DataContext = MyMusic
    End Sub
End Class

' Simple business object. 
Public Class Recording
    Public Sub New()
    End Sub
    Public Sub New(ByVal artistName As String, ByVal cdName As String, _
       ByVal release As DateTime)
        Artist = artistName
        Name = cdName
        ReleaseDate = release
    End Sub
    Private artistValue As String
    Private nameValue As String
    Private releaseDateValue As DateTime
    Public Property Artist() As String
        Get
            Return artistValue
        End Get
        Set(ByVal value As String)
            artistValue = value
        End Set
    End Property
    Public Property Name() As String
        Get
            Return nameValue
        End Get
        Set(ByVal value As String)
            nameValue = value
        End Set
    End Property
    Public Property ReleaseDate() As DateTime
        Get
            Return releaseDateValue
        End Get
        Set(ByVal value As DateTime)
            releaseDateValue = value
        End Set
    End Property
End Class

Public Class DateFormatter
    Implements IValueConverter

    ' This converts the DateTime object to the string to display. 
    Public Function Convert(ByVal value As Object, ByVal targetType As Type, _
        ByVal parameter As Object, ByVal language As System.String) As Object _
        Implements IValueConverter.Convert

        ' Retrieve the format string and use it to format the value. 
        Dim formatString As String = TryCast(parameter, String)
        If Not String.IsNullOrEmpty(formatString) Then

            Return String.Format(New CultureInfo(language), formatString, value)
        End If

        ' If the format string is null or empty, simply call ToString() 
        ' on the value. 
        Return value.ToString()
    End Function

    ' No need to implement converting back on a one-way binding.
    Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, _
        ByVal parameter As Object, _
        ByVal language As System.String) As Object _
        Implements IValueConverter.ConvertBack
        Throw New NotImplementedException()
    End Function
End Class

注解

Convert 方法的 targetType 参数使用不同的技术来报告类型系统信息,具体取决于你是使用 Microsoft .NET 还是 C++ 进行编程。

  • 对于 Microsoft .NET,此参数传递 System.Type 类型的实例。
  • 对于 C++/CX 和 C++/WinRT,此参数传递 TypeName 结构值。 TypeName::Kind 包含类型的简单字符串名称,类似于 Microsoft 。NET 的 Type.Name。 当绑定引擎调用转换器时,通过查找目标依赖属性的属性类型传递 targetType 值。 你可能出于以下两个原因之一在 Convert 实现中使用此值:
  • 转换器期望它始终返回特定类型的对象,并且你希望验证为其调用转换器的绑定是否正确使用转换器。 否则,可能会返回回退值或引发异常 (但请参阅) 下方的“来自转换器的异常”。
  • 转换器可以返回多个类型,并且你希望使用告知转换器应返回的类型。 例如,可以在同一转换器代码中实现对象到对象的转换和对象到字符串的转换。

语言 来自特定绑定的 ConverterLanguage 值,而不是系统值,因此应预期它可能是空字符串。

参数 来自特定绑定的 ConverterParameter 值,默认情况下为 null 。 如果转换器使用参数来修改它返回的内容,这通常需要一些约定来验证由绑定传递并由转换器处理的内容。 一种常见约定是传递字符串,这些字符串为转换器命名模式,从而产生不同的返回值。 例如,你可能具有“简单”和“详细”模式,这些模式返回不同的长度字符串,每个字符串都适合在不同的 UI 控件类型和布局中显示。

来自转换器的异常

数据绑定引擎不会捕获用户提供的转换器引发的异常。 Convert 方法引发的任何异常或 Convert 方法调用的方法引发的任何未捕获的异常都被视为运行时错误。 如果在绑定可以使用回退或以其他方式显示合理结果(即使发生转换失败)的情况下使用转换器,请考虑让转换器返回 DependencyProperty.UnsetValue ,并且不引发异常。 DependencyProperty.UnsetValue 是一个 sentinel 值,在依赖属性系统中具有特殊含义,传递此值的绑定将使用 FallbackValue

引发异常的另一种方法是返回原始 不变,并让绑定实例处理它可能对该值执行的操作。 在大多数情况下,失败的 UI 绑定不会是错误情况。 它们只是不会使用源值,而是使用 DependencyProperty.UnsetValue 不显示任何内容,或使用回退。

基于对执行操作的 try/catch 是 Convert 方法的常见实现模式,但由于上述原因,不应重新引发。

有关演示如何使用 参数和语言参数实现 Convert 方法的示例,请参阅 IValueConverter 接口。

适用于

另请参阅