Bagikan melalui


IValueConverter Antarmuka

Definisi

Mengekspos metode yang memungkinkan data dimodifikasi saat melewati mesin pengikatan.

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
Turunan
Atribut

Contoh

Contoh berikut menunjukkan cara mengimplementasikan antarmuka IValueConverter dan menggunakan pengonversi saat pengikatan data ke kumpulan objek.

Catatan

Jika Anda menggunakan C++/WinRT (atau C++/CX), lihat Memformat atau mengonversi nilai data untuk ditampilkan untuk contoh kode lainnya dalam menulis pengonversi nilai Anda sendiri. Topik itu juga membahas bagaimana Anda dapat menggunakan atribut ConverterParameter dengan fungsi pemformatan string 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();
        }
    }
}

Keterangan

Anda dapat membuat kelas yang memungkinkan Anda mengonversi format data antara sumber dan target dengan mewarisi dari IValueConverter. Misalnya, Anda mungkin ingin memiliki daftar warna yang Anda simpan sebagai nilai RGBA , tetapi menampilkannya dengan nama warna di UI. Dengan menerapkan Convert and ConvertBack, Anda dapat mengubah format nilai data saat diteruskan antara target dan sumber oleh mesin pengikatan. Anda harus selalu menerapkan Konversi dengan implementasi fungsional, tetapi cukup umum untuk menerapkan ConvertBack sehingga melaporkan pengecualian yang tidak diimplementasikan. Anda hanya memerlukan metode ConvertBack di pengonversi jika Anda menggunakan pengonversi untuk pengikatan dua arah, atau menggunakan XAML untuk serialisasi.

UnsetValue harus dikembalikan dari implementasi IValueConverter yang menyediakan konversi dalam pengikatan data ke properti dependensi, dalam hal apa pun di mana konverter tidak dapat mengonversi nilai sumber. Konverter tidak boleh melemparkan pengecualian untuk kasus tersebut dalam Konversi; ini akan muncul sebagai pengecualian run-time yang perlu Anda tambahkan penanganannya di UnhandledException atau lebih buruk namun muncul kepada pengguna sebagai pengecualian run-time aktual. Implementasi pengonversi harus mengikuti pola pengikatan umum bahwa setiap pengikatan yang gagal tidak melakukan apa pun dan tidak memberikan nilai, dan UnsetValue daripada null adalah nilai sentinel untuk kasus itu yang dipahami mesin pengikatan. Untuk informasi selengkapnya, lihat Pengikatan data secara mendalam.

Catatan

Untuk mengikat data ke pengonversi nilai kustom yang ditulis dalam ekstensi komponen Visual C++ (C++/CX), file header tempat kelas implementasi IValueConverter didefinisikan harus disertakan, secara langsung atau tidak langsung, di salah satu file code-behind. Untuk informasi selengkapnya, lihat Membuat yang pertama menggunakan C++.

Tip

Beberapa templat proyek default untuk aplikasi UWP termasuk kelas pembantu, BooleanToVisibilityConverter. Kelas ini adalah implementasi IValueConverter yang menangani skenario kontrol kustom umum di mana Anda menggunakan nilai Boolean dari kelas logika kontrol Anda untuk mengatur nilai Visibilitas dalam templat kontrol XAML.

Catatan migrasi

Dalam Windows Runtime, parameter bahasa untuk metode IValueConverter menggunakan string, dibandingkan dengan menggunakan objek CultureInfo seperti yang mereka lakukan dalam definisi Windows Presentation Foundation (WPF) dan Microsoft Silverlight dari antarmuka.

Metode

Convert(Object, TypeName, Object, String)

Memodifikasi data sumber sebelum meneruskannya ke target untuk ditampilkan di UI.

ConvertBack(Object, TypeName, Object, String)

Memodifikasi data target sebelum meneruskannya ke objek sumber. Metode ini hanya dipanggil dalam pengikatan TwoWay .

Berlaku untuk

Lihat juga