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

目標屬性的類型,做為 System.Type for Microsoft .NET 的類型參考 (,這是 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 介面。

適用於

另請參閱