語言

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

定義

在將原始資料傳送給目標物件以顯示於使用者介面前,先修改來源資料。

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

目標屬性的型別,作為型別參考。

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 還是 C++ 來報告類型系統資訊的不同技術。

  • 對於 Microsoft .NET,此參數傳遞 System.Type 類型的實例。
  • 對於 C++,這個參數會傳遞 TypeName 結構值。 TypeName::Kind包含型別的簡單字串名稱,類似於 Microsoft .NET 的。Type.Name 當綁定引擎呼叫轉換器時,透過查詢目標依賴屬性的屬性類型,傳遞 targetType 值。 你在 Convert 實作中使用這個值可能有兩個原因之一:
  • 你的轉換器預期它總是會回傳特定類型的物件,你要確認轉換器所需的綁定是否正確使用轉換器。 如果沒有,你可以回傳備援值,或拋出例外(但請參考下方「來自轉換器的例外」)。
  • 你的轉換器可以回送多種類型,你希望用量能讓轉換器知道應該回送哪一種。 例如,你可以在同一個轉換器程式碼中實作物件對物件的轉換和物件到字串的轉換。

語言 來自特定綁定的 ConverterLanguage 值,而非系統值,因此你應該預期它可能是空字串。

參數 來自特定綁定的 ConverterParameter 值,預設為 空 值。 如果你的轉換器用參數修改回傳內容,通常需要某種慣例來驗證綁定傳遞和轉換器處理的內容。 一個常見的慣例是傳遞字串來命名轉換器的模式,導致不同的回傳值。 例如,你可能會有「簡單」和「詳細」模式,分別回傳不同長度的字串,分別適合在不同介面控制類型和配置中顯示。

轉換器例外

資料綁定引擎不會捕捉由使用者提供的轉換器拋出的異常。 Convert 方法拋出的任何例外,或是 Convert 方法呼叫的方法拋出的任何未捕捉異常,都被視為執行時錯誤。 如果你在綁定能使用備援或即使轉換失敗也能顯示合理結果的情況下使用轉換器,請考慮讓轉換器回傳 DependencyProperty.UnsetValue ,並不要拋出例外。 DependencyProperty.UnsetValue 是一個哨兵值,在依賴屬性系統中具有特殊意義,傳遞此值的綁定會使用 FallbackValue。

另一個拋出例外的替代方案是回傳原始 值 不改,讓綁定實例自行處理該值可能的處理。 大多數情況下,失敗的 UI 綁定不會是錯誤案例。 他們只是不使用原始值,而是使用 DependencyProperty.UnsetValue 來顯示任何東西,或使用備援。

基於「做某件事」來嘗試/接住是 Convert 方法常見的實作模式,但基於上述原因,你不應該重擲。

關於如何利用 參數 與 語言 參數實作 Convert 方法的範例,請參見 IValueConverter 介面。

適用於

另請參閱