IValueConverter IValueConverter IValueConverter IValueConverter Interface

Definition

Exposes methods that allow the data to be modified as it passes through the binding engine.

public : interface IValueConverter
public interface IValueConverter
Public Interface IValueConverter
// You can't instantiate an interface directly in JavaScript. You can use objects that implement the interface, however.
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)

Examples

The following example shows how to implement the IValueConverter interface and use the converter when data binding to a collection of objects.

Important

If you are coding in Visual C++ component extensions (C++/CX), remove the ConverterParameter attribute from the last TextBlock, because that particular string value is specific to Microsoft .NET string formatting. Your entire element should look like this: <TextBlock Text="{Binding Path=ReleaseDate, Mode=OneWay, Converter={StaticResource FormatConverter}}" />.

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

Remarks

You can create a class that allows you to convert the format of your data between the source and the target by inheriting from IValueConverter. For example, you might want to have a list of colors that you store as RGBA values, but display them with color names in the UI. By implementing Convert and ConvertBack, you can change the format of the data values as they are passed between the target and source by the binding engine.

You should always implement Convert with a functional implementation, but it's fairly common to implement ConvertBack so that it reports a not-implemented exception. You only need a ConvertBack method in your converter if you are using the converter for two-way bindings, or using XAML for serialization.

Note

To data-bind to a custom value converter that is written in Visual C++ component extensions (C++/CX), the header file in which the IValueConverter implementation class is defined must be included, directly or indirectly, in one of the code-behind files. For more info, see Create your first using C++.

Tip

Some of the default project templates for a UWP app include a helper class, BooleanToVisibilityConverter. This class is an IValueConverter implementation that handles a common custom-control scenario where you use Boolean values from your control logic class to set the Visibility value in XAML control templates.

Migration notes

In the Windows Runtime, the language parameters for IValueConverter methods use strings, as opposed to using CultureInfo objects as they do in the Windows Presentation Foundation (WPF) and Microsoft Silverlight definitions of the interface.

Methods

Convert(Object, TypeName, Object, String) Convert(Object, TypeName, Object, String) Convert(Object, TypeName, Object, String) Convert(Object, TypeName, Object, String)

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

public : Platform::Object Convert(Platform::Object value, TypeName targetType, Platform::Object parameter, Platform::String language)
public object Convert(Object value, Type targetType, Object parameter, String language)
Public Function Convert(value As Object, targetType As Type, parameter As Object, language As String) As object
var object = iValueConverter.convert(value, targetType, parameter, language);
Parameters
value
Platform::Object Object Object Object

The source data being passed to the target.

targetType
TypeName Type Type Type

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

parameter
Platform::Object Object Object Object

An optional parameter to be used in the converter logic.

language
Platform::String String String String

The language of the conversion.

Returns
Platform::Object object object object

The value to be passed to the target dependency property.

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

Remarks

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

  • For Microsoft .NET, this parameter passes an instance of the System.Type type.
  • For Visual C++ component extensions (C++/CX), this parameter passes a TypeName structure value. TypeName::Kind contains the simple string name of the type, similar to Microsoft .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.

For an example that shows how to implement the Convert method using the parameter and language parameters, see the IValueConverter interface.

See Also

ConvertBack(Object, TypeName, Object, String) ConvertBack(Object, TypeName, Object, String) ConvertBack(Object, TypeName, Object, String) ConvertBack(Object, TypeName, Object, String)

Modifies the target data before passing it to the source object. This method is called only in TwoWay bindings.

public : Platform::Object ConvertBack(Platform::Object value, TypeName targetType, Platform::Object parameter, Platform::String language)
public object ConvertBack(Object value, Type targetType, Object parameter, String language)
Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, language As String) As object
var object = iValueConverter.convertBack(value, targetType, parameter, language);
Parameters
value
Platform::Object Object Object Object

The target data being passed to the source.

targetType
TypeName Type Type Type

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

parameter
Platform::Object Object Object Object

An optional parameter to be used in the converter logic.

language
Platform::String String String String

The language of the conversion.

Returns
Platform::Object object object object

The value to be passed to the source object.

Remarks

If you don't use a converter for TwoWay bindings it's acceptable to leave ConvertBack unimplemented (uses the template default from Visual Studio where it returns a NotImplementedException).

See Also

See Also