Your custom converter class must implement the IValueConverter or IMultiValueConverter interface or you will get a binding error. Here is an example of a simple pass through converter.
class BasicConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return value ;
}
}
Pass through converters are handy for debugging scenarios, but for this tip I want to show how to convert a number to an ordinal word, for example
Requires Free Membership to View
When you register, you'll begin receiving targeted emails from my team of award-winning writers. Our goal is to provide a unique online resource for developers, architects and development managers tasked with building and maintaining enterprise applications using Visual Basic, C# and the Microsoft .NET platform.
Hannah Smalltree, Editorial Director
public Window1()
{
InitializeComponent();
this.DataContext = new List() { 2,4,6,8,10,12};
}
Next, create the Ordinal Converter.
class NumberToOrdinalWordConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
var candidate = (int)value; switch (candidate)
{
// convert 1 through 10.
// all other numbers pass through the converter
case 1 :
return "First";
case 2 :
return "Second";
case 3:
return "Third";
case 4:
return "Fourth";
// etc.
default:
break;
}
return value; // no conversion
}
public object ConvertBack(object value, Type targetType,
object parameter,CultureInfo culture)
{
throw new NotImplementedException();
}
Here is the XAML for setting up the binding.
<Window x:Class="ValueConverterTips.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:data='clr-namespace:ValueConverterTips.Converters'
Title="Window1"
Height="300" Width="300">
<Window.Resources>
<data:BasicConverter x:Key='basicConverter' />
<data:NumberToOrdinalWordConverter x:Key='ordConverter' />
</Window.Resources>
<Grid>
<ListBox Margin='20'
ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding
Converter={StaticResource ordConverter},
Mode=OneWay}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
And here is the screenshot of the result.
This was first published in March 2010