Content Index Search
 

Create and apply a value converter

A value converter is a convenient way to convert data from one type to another. When you are binding the properties of objects in Microsoft® Expression Blend™ to data values or to other properties, the data types need to match. For example, you might want to convert a textbox string such as "123" to its corresponding integer value for a sliderbar, or convert a field such as Visibility.Hidden to a Boolean value such as false

A value converter implements the IValueConverter interface in code in a Microsoft® .NET Framework class. Both the Convert and ConvertBack methods must be implemented because the data binding engine calls these methods when it moves a value between the binding source and the binding destination. For more information, see IValueConverter Interface on MSDN.

To apply a value converter, you simply fill out the Value Converter field in the Create Data Binding dialog box when you are binding data to a property.

To create a value converter class

Paste the following code into a file named DoubleValueConverter.cs. This code contains the following two value converters:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Data;

namespace Microsoft.Expression.Samples
{
    /// <summary>
    /// DoubleToIntegerValueConverter provides a two-way conversion between
    /// a double value and an integer.
    /// </summary>
    public class DoubleToIntegerValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,
              System.Globalization.CultureInfo culture)
        {
            return System.Convert.ToInt32(value);
        }

        public object ConvertBack(object value, Type targetType,
            object parameter, System.Globalization.CultureInfo culture)
        {
            return System.Convert.ToDouble(value);
        }

    }

    /// <summary>
    /// DoubleToIntegerValueConverter provides a one-way conversion from
    /// a double value to a string representation of a Roman numeral.
    /// </summary>
    public class DoubleToRomanNumeralValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
        {
            return this.ConvertToRomanNumeral(System.Convert.ToInt32(value));
        }

        public object ConvertBack(object value, Type targetType,
            object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }

        private List<IntegerStringPair> romanStrings = null;

        private string ConvertToRomanNumeral(int input)
        {
            StringBuilder myBuilder = new StringBuilder();

            foreach (IntegerStringPair thisPair in this.PairSet)
            {
                while (input >= thisPair.Value)
                {
                    myBuilder.Append(thisPair.StringValue);
                    input -= thisPair.Value;
                }
            }

            return myBuilder.ToString();
        }

        private List<IntegerStringPair> PairSet
        {
            get
            {
                if (this.romanStrings == null)
                {
                    this.romanStrings = new List<IntegerStringPair>();
                    this.romanStrings.Add(new IntegerStringPair(1000, "M"));
                    this.romanStrings.Add(new IntegerStringPair(900, "CM"));
                    this.romanStrings.Add(new IntegerStringPair(500, "D"));
                    this.romanStrings.Add(new IntegerStringPair(400, "CD"));
                    this.romanStrings.Add(new IntegerStringPair(100, "C"));
                    this.romanStrings.Add(new IntegerStringPair(90, "XC"));
                    this.romanStrings.Add(new IntegerStringPair(50, "L"));
                    this.romanStrings.Add(new IntegerStringPair(40, "XL"));
                    this.romanStrings.Add(new IntegerStringPair(10, "X"));
                    this.romanStrings.Add(new IntegerStringPair(9, "IX"));
                    this.romanStrings.Add(new IntegerStringPair(5, "V"));
                    this.romanStrings.Add(new IntegerStringPair(4, "IV"));
                    this.romanStrings.Add(new IntegerStringPair(1, "I"));
                }

                return this.romanStrings;
            }
        }
    }

    /// <summary>
    /// IntegerStringPair provides an easy way to store integer and string pairs.
    /// </summary>
    public class IntegerStringPair
    {
        private int value;
        private string stringValue;
        public int Value
        {
            get
            {
                return this.value;
            }
        }
        public string StringValue
        {
            get
            {
                return this.stringValue;
            }
        }
        public IntegerStringPair(int value, string stringValue)
        {
            this.value = value;
            this.stringValue = stringValue;
        }
    }
}

To apply a value converter to a property

In the following procedure, the value converters in the preceding code are applied to the value of a Slider object when the value is bound to two Label objects. The result is that the labels display the integer and Roman numeral representations of the Slider value.

  1. Add the DoubleValueConverter.cs file to your project in Expression Blend. On the Project menu, click Add Existing Item, browse to the DoubleValueConverter.cs file, and then click Open.
    Tip Alternatively, you can build your DoubleValueConverter.cs into a .dll file, and add a reference to the .dll to your project.
  2. Build your project (CTRL+SHIFT+B) to make the value converter classes available to your project.
  3. From the Toolbox, add two Label controls and a Slider control to the artboard. Lay them out so that they have plenty of room.
  4. With the Slider object selected under Objects and Timeline, set the following properties under Common Properties in the Properties panel:
    • Set LargeChange to 10. This is the incremental change that occurs when you click the Slider.
    • Set Maximum to 2001. The Slider will go from 0 to 2001.
    • Set SmallChange to 1. This is the incremental change that occurs when you use your arrow keys to move the Slider.
  5. With the first Label object selected under Objects and Timeline, click the Content property under Common Properties in the Properties panel. Click Data Binding on the drop-down list that appears.
    The Create Data Binding dialog box opens.
  6. Select All Properties in the Show dropdown box.
  7. On the Element Property tab, select Slider from the tree of elements under Scene elements.
  8. On the Element Property tab, select Value : (Double) under Properties. This will bind the content of the label to the value of the slider.
  9. Click the Expand button Dialog expander button on the Create Data Binding dialog box to view the advanced settings.
  10. Next to the Value converter drop-down box, click the Add New Value Converter button.
    The Add Value Converter dialog box opens.
  11. Expand the name of your project and the Microsoft.Expression.Samples namespace, select the DoubleToIntegerValueConverter, and then click OK.
    Tip If you do not see your value converter, make sure that you have added the source file to the project and that you have built your project (CTRL+SHIFT+B).
  12. In the Create Data Binding dialog box, click Finish.
    The first Label object will now display an integer representation of the slider.
    Note Notice that your slider object has been given the name of Slider. Objects in your application must be named in order for them to be referenced from elsewhere in your application, such as during data binding. Expression Blend sets a name for you.
  13. Repeat steps 5 through 11 with the second label, but select DoubleToRomanNumeralValueConverter in the Add Value Converter dialog box.
  14. Test your project (F5). Move the slider to see the values updated in the two labels.