Share via


IValueConverter Interface

Definition

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

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
Derived
Attributes

Examples

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

Note

If you're using C++/WinRT (or C++/CX), then see Formatting or converting data values for display for more code examples of authoring your own value converter. That topic also discusses how you could use the ConverterParameter attribute with C++ string-formatting functions.

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

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.

UnsetValue should be returned from an IValueConverter implementation that provides conversion in a data binding to a dependency property, in any case where the converter is unable to convert a source value. Converters shouldn't throw exceptions for that case in Convert; these will surface as run-time exceptions that you'd need to add handling for in UnhandledException or worse yet appear to users as actual run-time exceptions. Converter implementations should follow the general binding pattern that any failed binding does nothing and does not provide a value, and UnsetValue rather than null is the sentinel value for that case that the binding engine understands. For more info, see Data binding in depth.

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)

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

ConvertBack(Object, TypeName, Object, String)

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

Applies to

See also