Using IValueConverter to format binding values in WPF

First we need implement the value converter, to accomplish this we need to create a new class that implements System.Windows.Data.IValueConverter, this interface works only for simple binding. If you need to use multi binding you will need implement System.Windows.Data.IMultiValueConverter. In the attached sample both interfaces are implemented.

After create the value converter class we have to define a resource (in XAML) pointing the class:

<loc:FormatConverter x:Key="formatConverter" /> 

Finally, we can use the FormatConverter class as follows:

<TextBlock Text="{Binding Text, Converter={StaticResource formatConverter},
                ConverterParameter=The text is \'{0}\'}" /> 
<TextBlock Text="{Binding DateTime, Converter={StaticResource formatConverter},
                ConverterParameter={}{0:d}}" />
<TextBlock Text="{Binding DateTime, Converter={StaticResource formatConverter},
                ConverterParameter={}{0:HH:mm:ss}}" />

You can download the full sample here.

2 Comments

  • Error 1 Names and Values in a MarkupExtension cannot contain quotes. The MarkupExtension arguments ' Text, Converter={StaticResource formatConverter}, ConverterParameter=The text is '{0}'}' are not valid. Line 10 Position 14.

    From your sample

  • You will need escape the text in order to work, for example ConverterParameter=The text is \'{0}\'. The code and the post is already updated.

Comments have been disabled for this content.