Sometimes the value you want to display needs to be transformed from the original data before being bound to a XAML element. For instance, formatting a telephone number, or adding brackets to a negative balance on an account. To accomplish this task a Value Converter is used. A Value Converter is simply a class that implements the IValueConverter interface (located in the System.Windows.Data namespace). This interface contains two methods, Convert, and ConvertBack. It is not necessary to implement the ConvertBack method unless you are persisting data back to a data source and need the reverse transformation from the visual back to the persisted value. It is important to remember that Value Converters can take in any value and return any type of object, for instance, an integer can be transformed into a string, and a string can be turned into a user control. In the example provided below, an integer value is converted to a User Control that has the ability to display a 5 star rating. Here is the XAML of the FiveStarRating user control which is made up of 5 paths in the shape of a star:
Source code for the FiveStarRating user control is as follows, contains the logic to fill the correct number of stars dependent on the Rating property of the instance:
The Rating property of the FiveStarRating user control has been defined as a DependencyProperty, so it is possible to bind directly to it, but in this example, we will be using this user control as the result of a value converter transformation instead. The class definition and data being bound is defined in this previous blog post. The value converter we will implement will convert the integer ImageRating value and transform it into a bound FiveStarRating user control. The listing for the value converter is as follows:
In order to utilize this Value Converter during data binding, it must first declare the namespace in the window tag, in this case the namespace is ValueConverter which resides in the current project assembly:
Then define an instance of the value converter class in Resources:
This instance of the RatingConverter can now be used in the data template. In order to utilize the rating converter, identify the resource (identified by the key in Resources, in this case RatingConverter) and assign it to the converter property of the binding expression.
This binding expression passes in the value stored in the ImageRating property of the object being bound into the Convert method of the RatingConverter value converter. The value converter then instantiates a new FiveStarRating user control, assigns the integer value to its Rating property, and returns the user control instead of the original integer ImageRating value. The user control is then rendered in the Label control.
Complete source code for this sample is available here.