Share via


Try it: Convert data from one type to another

A value converter is a convenient way to convert data from one type to another. When you bind a property value of an object in Microsoft Expression Blend to a data value or to another property value, the value types must match. For example, you might want to convert a text box string such as "123" to its corresponding integer value for a slider bar, or convert a property 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, complete the Value Converter field in the CreateDataBinding dialog box when you are binding data to a property.

To create a value converter class

This procedure provides an example of a .NET class, written in C#, that can be added only to a project that already uses C# for its code-behind files. However, there is more than one way to add code to a project. You could alternatively use Microsoft Visual Studio to compile the class into a .dll and then add a reference to the .dll file in your project.

For more information, see Add or remove a reference.

  1. Right-click your project in the Projects panel, and then click Add New Item.

  2. In the New Item dialog box, click Class, enter DoubleValueConverter.cs in the Name field, and then click OK.

    A new code file is created, in the language that your solution is using. For the purposes of this procedure, this language is C#. The file is added to your project and opened on the artboard.

  3. In the DoubleValueConverter.cs file, delete the following class definition:

    public class DoubleValueConverter
    {
        public DoubleValueConverter()
        {
            // Insert code required on object creation below this point.
        }
    }
    
  4. Replace the deleted code with the following code, which contains the following two value converter classes:

    • DoubleToIntegerValueConverter   Provides a two-way conversion between a double value and an integer.

    • DoubleToRomanNumeralValueConverter   Provides a one-way conversion from a double value to a string representation of a Roman numeral.

        /// <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>
        /// DoubleToRomanNumeralValueConverter 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;
            }
        }
    
  5. Build (CTRL+SHIFT+B) your solution to see if there are any errors.

    Tip

    Building compiles the code files and makes the classes available to Expression Blend (for example, in the Create Data Binding dialog box). If you add new classes to your code file, you will have to rebuild your solution to make them available to Expression Blend.

To apply a value converter to a property

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

  1. In the Tools panel, right-click the bottom tool group, and then select the Slider Cc295312.b478d0b9-7525-47cb-b633-0007e08432d4(en-us,Expression.30).png control from the list that appears.

  2. Draw a slider control on the artboard in your main document.

  3. With the new slider object selected, locate the following properties under Common Properties in the Properties panel and set their values as follows:

    • Set LargeChange to 10. This is the incremental change that occurs when you click the slider bar.

    • 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.

  4. In the Tools panel, right-click the tool group second from the bottom, and then select the TextBox Cc295312.b5206bf1-18c8-491f-8239-3e542b2ca147(en-us,Expression.30).png control from the list that appears.

  5. Draw two text box controls on the artboard next to the slider object.

  6. With the first text box object selected, locate the Text property under Common Properties in the Properties panel. You will bind the Text property to the value of the slider.

  7. Click Advanced property options Cc295312.12e06962-5d8a-480d-a837-e06b84c545bb(en-us,Expression.30).png, and then click Data Binding from the list that appears.

  8. In the Create Data Binding dialog box, click the Element Property tab. This is where you bind internal values to properties.

  9. Expand the tree of elements under Scene elements, and then select the [Slider] object.

  10. Under Properties, select Value : (Double).

    This binds the content of the text box to the value of the slider.

  11. Click Show advanced properties Cc295312.de239c9d-42ce-4f5e-83b9-5f9924c0431f(en-us,Expression.30).png, and then, next to Value converter, click Add new value converter Cc295312.3f9fe48b-caf8-4989-8a91-017ba1e0cb77(en-us,Expression.30).png.

  12. In the Add Value Converter dialog box, select DoubleToIntegerValueConverter, and then click OK.

    Tip

    If you do not see your value converter, make sure that the source file that you created in the preceding procedure, DoubleValueConverter.cs, is added to the project, and that you have built your project (CTRL+SHIFT+B).

  13. In the Create Data Binding dialog box, click OK.

    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 for them to be referenced from elsewhere in your application, such as during data binding. Expression Blend creates a name for you.

  14. Repeat steps 6 through 13 with the second text box, but this time, select DoubleToRomanNumeralValueConverter in the Add Value Converter dialog box.

  15. Run your project (F5). Move the slider to see the values updated in the two labels.

    Cc295312.f1241b72-d14a-4de2-9d99-332418f84561(en-us,Expression.30).png

    Without using the value converter, a text box that displays the value of a slider would display many decimal places.

    Cc295312.0279e814-a5af-4322-84d4-754083a57f83(en-us,Expression.30).png

See also

Tasks

Bind an object to user input or to other internal values

Concepts

Style a control that displays data

Displaying data