Introduction
In often cases data travel from the source to the target without any change, but this is not the case we are interested into. Our data source could be some low level information which we want to encapsulate from showing directly on user interface. For example, we might have some numeric codes which we want to show as more human readable strings. So when we have achieved this, we need to so some conversion. And also if we are doing two way binding, we need to also handle the converse, which is taking user input data and converting it to a representation suitable for storage in the appropriate data object.
Value Converter Class
This Silverlight class is responsible for converting source data just before it is displayed in the target and also doing job of converting the new target value just before it is supplied back to the source.
When we can use Value Converter Class
We can use the ValueConverter class to:
- Convert data into string representation: converting a number into a string.
- Create specific type of Silverlight object: we can read a block of binary data and create a image object that can be later bound to an image element.
- Conditionally change an element's property based on bound control: suppose we want to change the background color of an element depending on some range, we can make use of value converter class here.
Okay, so let us take the above three scenarios one by one and explore what value converter has to offer us.
Before we start we will create a Silverlight project and we will create a GUI for displaying the data from XML data source.
Code for accessing WCF service is below.
Here I have created a XML data source and we are accessing it via WCF service as collection of object and binding it into listbox. Later on item selection we are further binding items into textboxes. Look into xaml you will find that I have written binding expression of each.
Figure 1: Display UI

See the WCF code into project itself. Here we will more concentrate on Value converter.
Now since we have WCF service doing job for us and we are getting data to display in our GUI, now its time to do some actual data conversions. So we will take one by one scenario.
Scenario 1: Formatting String.
Value converters are the perfect tool for formatting numbers that need to be displayed as text. For example, consider the Product.UnitCost property. It's stored as a decimal; and, as a result, when it's displayed in a text box, you see value with more decimal places. Not only does this display format show more decimal places than you'd probably like, but it also leaves out the currency symbol. A more intuitive representation is the currency-formatted value $2.99
So we will create a value converter class to this formatting.
Steps involved in creating value converter class;
- We need to create a class that implements IValueConverter (from the System.Windows.Data
- Namespace). We place this class in our Silverlight project, which is where the conversion takes place–and not in the web service.
- Then we need to implement a
Convert() method that changes data from its original format to its display format.
- At last we need to implement a
ConvertBack() method that does the reverse and changes a value from display format to its native format.
So now add a new class and name it PriceConverter.cs in Silverlight project, not in the web service one. Also add System.Window.Data assembly.
Open PriceConverter.cs, and write below codes.
Here we are converting string into currency. This code uses the culture settings that apply to the current thread. A computer that's configured for another locale may display a different currency symbol. If this isn't the result we want (for example, we always want the dollar sign to appear), you can specify a culture using the overload of the ToString() method.
Now below is code to converse , convert user input data into data source format.
Now this is going to be tricky and not so straight forward. This is because Parse() or TryParse() cannot handle currency conversion. The solution is to use an overloaded version of the Parse() or TryParse() method that accepts a System.Globalization.NumberStyles value. If you supply NumberStyles.Any, you can successfully strip out the currency symbol, if it exists.
Now To put this converter into action, you need to begin by mapping your project namespace to an XML namespace prefix you can use in your markup. Here's an example that uses the namespace prefix converter and assumes your value converter is in the namespace DataBinding:
So open main.xmal and add below xmal code.
now we will add this attribute to the <UserControl> start tag at the top of your markup.
Now we can point to it in your binding using a StaticResource reference:
So when item from listbox is selected, unit cost is bind to above textbox, and it calls Convert method from our value converter class .i.e. price converter class.
Run and see now we have dollar sign,
Figure 2: Displaying Unit Cost with Dollar Sign

You can see now the unit cost is showing up with dollar sign.
Scenario Two: How to create object with the help of Value Converter.
Suppose we have an scenario where we have stored picture data stored as a byte of array in a field in a database. we can convert the binary data into a Bitmap image object and can store that as a part of project. But this approach is not flexible because we may need to create more than one object representation of the image in scenario where our data library is used by Silverlight and WPF as well.
In this case, it makes sense to store the raw binary data in your data object and convert it to a BitmapImage object using a value converter.
Open product.cs and check for ProductImagePath property.
The ProductImage field includes the file name but not the full URI of an image file. This gives us the flexibility to pull the image files from any location. The value converter has the task of creating a URI that points to the image file based on the ProductImage field and any website we want to use. The root URI is stored using a custom property named RootUri, which defaults to the same URI where the current web page is located.
Now its time to creata class for ImagePathConverter which will implement Value Converter class for creating object:
Add a new class and name it as ImagePathConverter.cs and write below code.
To use this converter, begin by adding it to Resources.
And now we need to write source for image
We are ready now , so Prss F5 , get all products and click on any listbox items
Figure 3: Dsiplaying Image

You can see, we are able to get image.Cools , isin't.
Scenario Three: Conditional formatting
Potential of value converter is not justto format data for representation , but they can also be used to format other appearance related aspect of an element based on a data rules. Now the scenario is lke we want to highlight high priced items with a different backgroud.
So let us add another class and name it PriceToBackgroundConverter.cs
Write the below code inside it;
You notice that we have used brushes instead of colors so that we can create more advanced highlight effects using gradients and background images. And if we want to keep the standard,
Transparent background (so the background of the parent elements is used), set the DefaultBrush or HighlightBrush property to null.
Once again, the value converter is carefully designed with reusability in mind. Rather than hard-coding the color highlights in the converter, they're specified in the XAML by the code that uses the converter:
So now all we need to do is use this converter to set the background of an element, such as the Border that contains all the other elements:
In many scenarios, we'll need to pass information to a converter beyond the data we want to convert. In this example, PriceColorConverter needs to know the highlight color and minimum price details, and this information is passed along through properties.
However, we can pass a single object (of any type) to a converter through the binding expression, by setting the ConverterParameter property. Here's an example that uses this approach to supply the minimum price:
The parameter is passed as an argument to the Convert() method. Here's how you can rewrite the earlier example to use it:
But I personally prefer property-based approach is preferred. It's clearer, more flexible, and Strongly typed.
So press F5 and see the result.
Figure 4: For item with unit cost less than 50, border background won’t change.

For item , whose unit price is more than 50 , backgroud chnages
Figure 5: Displaying change backgroud for items whose unit price is > 50

Summary
By this we come to an end of our lesson Data conversion using Value Converter class and we tried this using three different scenarios.
About Vishal Nayan
 |
Vishal is a seasoned professional with hand on experience on Microsoft technologies.
He always look for challenging assignment that allows him to learn newer technologies while utilizing his experience of project development and software engineering ethics.
In spare time vishal can be found read...
This author has published 4 articles on DotNetSlackers. View other articles or the complete profile here.
|
You might also be interested in the following related blog posts
New Entity Framework Feature CTP for VS2010 Beta 2
read more
Introducing Versatile DataSources
read more
Entirely unobtrusive and imperative templates with Microsoft Ajax Library Preview 6
read more
Project Turing: Beginning RIA Svcs
read more
Building a class browser with Microsoft Ajax 4.0 Preview 5
read more
RadScheduler for Silverlight learning series, part 4: So what is RecurrenceExceptionHelper?
read more
Project Turing: Beginning RIA Services
read more
Self-reference hierarchy with Telerik TreeView for Silverlight
read more
Business Apps Example for Silverlight 3 RTM and .NET RIA Services July Update: Part 23: Azure
read more
Telerik Launches RadControls for Silverlight 3 for Line-of-Business Application Development
read more
|
|
Please login to rate or to leave a comment.