Creating an ordinal binding converter

Creating an ordinal binding converter

In a standard WPF binding, the value from the data source is synchronized and shown in the data target. One option when creating a binding is to specify a value converter. Value converters live a simple life. They take an incoming value and convert it to a value of another type. If a value converter is specified in binding, the source data is funneled to the converter before arriving at the binding destination. In the case of a two way binding, it can also convert the data on the return trip to the data source. This makes it simple to change values from a number (3) to a string (3rd) or change a number range (less than ten) to a color brush(Red). The possibilities are endless, as you can write code to covert from any .NET type to an alternate .NET type.

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

    By submitting your registration information to SearchWinDevelopment.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchWinDevelopment.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

the number 2 is converted to the word "second". First, take a look at the data source for the binding as shown in this C# code.


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

Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.