The first thing we should ask is; what is Value Converter(s)?
Well, to say it in simple words it is a Converter that converts value based on input as Source and provides output as Target.
Hope the following figure make things easier to understand:
As you can see from the above image we have both way arrows in between Source and Target. That means: the value converter not only designed to take input from the target and modify the source, it also works when source data is updated on target. As you are familiar with two way bindings in WPF.
We will straight away create a WPF Application and create simple converters to understand it.
Creating WPF Application
Fire up Visual Studio 2008 and Create a WPF Application, name it as ConvertersInWPF.
Now let's think what simple converter we can use!
Let's say we will create one or more Converters. So we will keep inside a folder:
Now add a class to the Converter Folder, name it as StatusToColor.cs
Here's the idea, we will have a list of Requests and we will display the status of the request in colors.
Let's have the following entity class that represent Request structure.
As you see in above code display we have an Enum as Status and we have 5 values inside of it; such as: Submitted, Assigned, InProgress, Resolved, and Closed.
Now based on above information we will modify our StatusToColor.cs
Implement IValueConverter in the above class.
As the namespace is not referred, we have to type it upto end and after resolving you would see the following namespace to be used.
Now we have to implement the methods in this Interface. So resolve the interface again.
Select the Implement interface option: the following methods would be defined as follows:
As we discussed in the beginning that the Source and Target can convert each other so that's why we have two methods defined. Convert would do conversion from Source -> Target and ConvertBack would do conversion from Target -> Source.
For the time being we will proceed with Convert method.
First we will define the Enum here again.
We can use the same name but for understanding I am giving a different name.
Remove the throw new Exception(); and replace with following code.
The above code display for converting and returning is a very simple logic to convert.
Now for user's knowledge about the colr use we would put the colors with some information.
Now we have bind the converter in the XAML, for that first thing we have to do is to use the namespace.
Now we have customized the DataGrid, to have a TextBoxColumn and a TemplateColumn to display the Status as defined Color.
Now for the Rectangle in TemplateColumn we will fill using the Converter:
We are good to go, and run the application. But before that let's have some sample data to display.
You would see the colors are reflected as per the data given.
Hope this article helps.