IValueConverter interface

Applies to Windows and Windows Phone

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

Syntax

Public Interface IValueConverter

Attributes

[Version(0x06020000)]
[WebHostHidden()]

Members

The IValueConverter interface has these types of members:

Methods

The IValueConverter interface has these methods. It also inherits methods from the Object class.

MethodDescription
Convert Modifies the source data before passing it to the target for display in the UI.
ConvertBack Modifies the target data before passing it to the source object. This method is called only in TwoWay bindings.

 

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 Windows Store app using C++.

Tip  Some of the default project templates for a Windows Store 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.

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 C++/CX, remove the ConverterParameter attribute from the last TextBlock, because that particular string value is specific to .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>


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

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

Binding
XAML data binding sample
Data binding overview

 

 

Show:
© 2014 Microsoft