In a recent Windows Phone 7 app I needed to bind specific measurement values from a class to the UI, this is a relatively straightforward process, however, I also needed to be able to show units of measurement without really affecting the base class. In the class that I defined I created a parameter that represented the height of a person in inches or centimeters. Keeping the unit of height generic within the class means that I need to a way convert and display the value in either feet\inches or meters\centimeters during the binding process.

Thankfully Silverlight makes available the Binding.Converter Property that takes and convert any value before displaying it on the page before completing binding. In order to set it up you will need to import the namespace for the Converter class  into the xaml page as follows:


Within the user control resource section of the page make a direct reference to your class in following format:

  <local:HeightToStringConverter x:Key="HeightConvert"/></UserControl.Resources>

The control and property that is being bound to will need a direct reference to the key defined in the resource section along with an indication of whether this is one-way or two-way mode. In my example it is one a one way conversion, meaning, that I will need be modifying values that will be received by my object.

<TextBlock Name="textHeight" Text="{Binding Height, Mode=OneWay, Converter={StaticResource HeightConvert}}" />

This serves as the actual class definition which implements IVal ueConverter and allows us to implement Convert (one way) and ConvertBack (two way). In my example I define Convert and allow a conversion to string that formats the height to have units of measure based on the imperial or metric measurement system.

// Within the Convert namespace
public class HeightToStringConverter : IValueConverter
  // Define the Convert method 
  public object Convert(object value, Type targetType, object parameter,System.Globalization.CultureInfo culture)
    int height = (int)value;
    int feet = 0;
    int inches = 0;
    int meters = 0;
    int cms = 0;

    // value is the data from the source object.
    if (App.ViewModel.BMICalculator.MeasureType == MEASURETYPE.IMPERIAL)
      feet = height / 12;
      inches = height - (feet * 12);
      return String.Format("{0} feet {1} inches", feet, inches);
      meters = height / 100;
      cms = height - (meters * 100);
      return String.Format("{0} meters {1} cms", meters, cms);;

  // Define the ConvertBack method
  public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    return value;

Comment Section

Comments are closed.