Compartilhar via


Try it: Create and apply a value converter

This page applies to WPF and Silverlight 2

A value converter is a convenient way to convert data from one type to another. When you bind the properties of objects in Microsoft Expression Blend to data values or to other properties, the data 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 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 just complete the Value Converter field in the CreateDataBinding dialog box when you are binding data to a property.

Note

The second procedure in this topic applies the value converter by using element-to-element binding, which is not supported in Silverlight 2. However, you can apply value converters to data-binding operations that use a CLR data source.

To create a value converter class

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

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

    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;
            }
        }
    }
    

Cc295312.7e183f1f-37d8-4dcb-980c-19a5d61ca087(en-us,Expression.10).gifBack to top

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 a project in Expression Blend. On the Project menu, click AddExistingItem, browse to the DoubleValueConverter.cs file, and then click Open.

    Note

    Make sure your project was created with the Visual C# Language option. 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 lots of room.

  4. With the Slider object selected under Objects and Timeline, set the following properties under CommonProperties 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 ObjectsandTimeline, click the Content property under Common Properties in the Properties panel. Click DataBinding on the drop-down list that appears. The CreateDataBinding dialog box opens.

  6. On the ElementProperty tab, select Slider from the tree of elements under Sceneelements.

  7. On the ElementProperty tab, select All Properties in the Show drop-down list, and then select Value : (Double) under Properties. This binds the content of the label to the value of the slider.

  8. Click the Expand Cc295312.81e110f1-4068-4299-957d-0693cea95088(en-us,Expression.10).png button on the CreateDataBinding dialog box to view the advanced settings.

  9. Next to the Valueconverter drop-down box, click the AddNewValueConverter button. The AddValueConverter dialog box opens.

  10. 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).

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

  12. Repeat steps 5 through 11 with the second label, but select DoubleToRomanNumeralValueConverter in the Add Value Converter dialog box.

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

Cc295312.7e183f1f-37d8-4dcb-980c-19a5d61ca087(en-us,Expression.10).gifBack to top