IValueConverter.Convert method

Applies to Windows and Windows Phone

Modifies the source data before passing it to the target for display in the UI.

Syntax


Object^ Convert(
  Object^ value, 
  TypeName targetType, 
  Object^ parameter, 
  String^ language
)

Parameters

value

Type: System.Object [.NET] | Platform::Object [C++]

The source data being passed to the target.

targetType

Type: System.Type [.NET] | TypeName [C++]

The type of the target property, as a type reference (System.Type for .NET, a TypeName helper struct for C++/CX).

parameter

Type: System.Object [.NET] | Platform::Object [C++]

An optional parameter to be used in the converter logic.

language

Type: System.String [.NET] | Platform::String [C++]

The language of the conversion.

Return value

Type: System.Object [.NET] | Platform::Object [C++]

The value to be passed to the target dependency property.

Remarks

The targetType parameter of the Convert method uses different techniques of reporting the type system info, depending on whether you're programming with .NET or C++/CX.

  • For .NET, this parameter passes an instance of the System.Type type.
  • For C++/CX, this parameter passes a TypeName structure value. TypeName::Kind contains the simple string name of the type, similar to .NET's Type.Name.

When the converter is invoked by the binding engine, the targetType value is passed by looking up the property type of the target dependency property. You might use this value in your Convert implementation for one of two reasons:

  • Your converter has the expectation that it's always going to return objects of a specific type, and you want to verify that the binding that the converter is called for is using the converter correctly. If not, you might return a fallback value, or throw an exception (but see "Exceptions from converters" below).
  • Your converter can return more than one type, and you want the usage to inform your converter which type it should return. For example, you could implement an object-to-object conversion and an object-to-string conversion within the same converter code.

language comes from the ConverterLanguage value of a specific binding, not system values, so you should expect that it might be an empty string.

parameter comes from the ConverterParameter value of a specific binding, and is null by default. If your converter uses parameters to modify what it returns, this usually requires some convention for validating what is passed by the binding and handled by the converter. A common convention is to pass strings that name modes for your converter that result in different return values. For example you might have "Simple" and "Verbose" modes that return different length strings that are each appropriate for display in different UI control types and layouts.

Exceptions from converters

The data binding engine does not catch exceptions that are thrown by a user-supplied converter. Any exception that is thrown by the Convert method, or any uncaught exceptions that are thrown by methods that the Convert method calls, are treated as run-time errors. If you are using the converter in situations where the binding can use fallbacks or otherwise show reasonable results even if a conversion failure occurs, consider having your converter return DependencyProperty.UnsetValue and not throw exceptions. DependencyProperty.UnsetValue is a sentinel value that has special meaning in the dependency property system, and bindings that are passed this value will use FallbackValue.

Another alternative to throwing exceptions is to return the original value unchanged, and let the binding instance handle what it might do with that value. In most cases UI bindings that fail won't be error cases. They just won't use the source value and will instead use DependencyProperty.UnsetValue to show nothing, or use fallbacks.

try/catch based on doing something to value is a common implementation pattern for the Convert method, but you shouldn't rethrow, for the reasons mentioned above.

Examples

The following example shows how to implement the Convert method using the parameter and language parameters.


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


Requirements

Minimum supported client

Windows 8

Minimum supported server

Windows Server 2012

Minimum supported phone

Windows Phone 8.1 [Windows Runtime apps only]

Namespace

Windows.UI.Xaml.Data
Windows::UI::Xaml::Data [C++]

Metadata

Windows.winmd

See also

IValueConverter
ConvertBack
XAML data binding sample
Data binding overview

 

 

Show:
© 2014 Microsoft