Share via


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 的 System.Type (參考,這是 Visual C++ 元件延伸模組的 TypeName 協助程式結構, (C++/CX) ) 。

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();
        }
    }
}

備註

Convert 方法的 targetType 參數會使用不同的技術來報告類型系統資訊,視您使用 Microsoft .NET 或 Visual C++ 元件延伸模組進行程式設計, (C++/CX) 而定。

  • 針對 Microsoft .NET,此參數會傳遞 System.Type 類型的實例。
  • 若為 Visual C++ 元件延伸模組 (C++/CX) ,此參數會傳遞 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 介面。

適用於

另請參閱