Problem solve Get help with specific problems with your technologies, process and projects.

Creating an ordinal binding converter

When creating an ordinal binding converter the possibilities are endless, as you can write code to covert from any .NET type to an alternate .NET type.

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 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 last published in March 2010

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchCloudComputing

SearchSoftwareQuality

TheServerSide.com

SearchCloudApplications

Close