Share via


IValueConverter.Convert(Object, TypeName, Object, String) Método

Definición

Modifica los datos de origen antes de pasarlos al destino para mostrarlos en la interfaz de usuario.

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

Parámetros

value
Object

Platform::Object

IInspectable

Los datos de origen que se pasan al destino.

targetType
TypeName Type

Tipo de la propiedad de destino, como referencia de tipo (System.Type para Microsoft .NET, un struct auxiliar TypeName para C++/CX y C++/WinRT).

parameter
Object

Platform::Object

IInspectable

Parámetro opcional que se va a usar en la lógica del convertidor.

language
String

Platform::String

winrt::hstring

Idioma de la conversión.

Devoluciones

Object

Platform::Object

IInspectable

Valor que se va a pasar a la propiedad de dependencia de destino.

Ejemplos

En el ejemplo siguiente se muestra cómo implementar el método Convert mediante el parámetro y los parámetrosde lenguaje .

//
// 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

Comentarios

El parámetro targetType del método Convert usa diferentes técnicas de generación de informes de la información del sistema de tipos, en función de si está programando con Microsoft .NET o C++.

  • Para Microsoft .NET, este parámetro pasa una instancia del tipo System.Type .
  • Para C++/CX y C++/WinRT, este parámetro pasa un valor de estructura TypeName . TypeName::Kind contiene el nombre de cadena simple del tipo, similar a Microsoft . NET es Type.Name. Cuando el motor de enlace invoca el convertidor, el valor targetType se pasa buscando el tipo de propiedad de la propiedad de dependencia de destino. Puede usar este valor en la implementación convertir por uno de estos dos motivos:
  • El convertidor tiene la expectativa de que siempre va a devolver objetos de un tipo específico y desea comprobar que el enlace al que se llama al convertidor está usando el convertidor correctamente. Si no es así, puede devolver un valor de reserva o producir una excepción (pero vea "Excepciones de convertidores" a continuación).
  • El convertidor puede devolver más de un tipo y desea que el uso informe al convertidor de qué tipo debe devolver. Por ejemplo, podría implementar una conversión de objeto a objeto y una conversión de objeto a cadena dentro del mismo código de convertidor.

language procede del valor ConverterLanguage de un enlace específico, no de valores del sistema, por lo que debe esperar que sea una cadena vacía.

el parámetro procede del valor ConverterParameter de un enlace específico y es null de forma predeterminada. Si el convertidor usa parámetros para modificar lo que devuelve, esto normalmente requiere alguna convención para validar lo que pasa el enlace y controlado por el convertidor. Una convención común es pasar cadenas que asignen modos de nombre para el convertidor que dan lugar a valores devueltos diferentes. Por ejemplo, podría tener modos "Simples" y "Detallados" que devuelven cadenas de longitud diferentes que son adecuadas para mostrarse en diferentes tipos y diseños de control de interfaz de usuario.

Excepciones de convertidores

El motor de enlace de datos no detecta excepciones producidas por un convertidor proporcionado por el usuario. Cualquier excepción producida por el método Convert, o las excepciones no detectadas que producen los métodos a los que llama el método Convert, se tratan como errores en tiempo de ejecución. Si usa el convertidor en situaciones en las que el enlace puede usar reservas o mostrar resultados razonables incluso si se produce un error de conversión, considere la posibilidad de que el convertidor devuelva DependencyProperty.UnsetValue y no produzca excepciones. DependencyProperty.UnsetValue es un valor centinela que tiene un significado especial en el sistema de propiedades de dependencia y los enlaces que se pasan este valor usarán FallbackValue.

Otra alternativa a producir excepciones es devolver el valor original sin cambios y permitir que la instancia de enlace controle lo que podría hacer con ese valor. En la mayoría de los casos, los enlaces de interfaz de usuario que producen errores no serán casos de error. Simplemente no usarán el valor de origen y, en su lugar, usarán DependencyProperty.UnsetValue para mostrar nada o usar reservas.

try/catch basado en hacer algo en valor es un patrón de implementación común para el método Convert, pero no debe volver a iniciarse, por los motivos mencionados anteriormente.

Para obtener un ejemplo que muestra cómo implementar el método Convert mediante el parámetro y los parámetros de lenguaje , vea la interfaz IValueConverter .

Se aplica a

Consulte también