Why Type Converters in WPF

+1 vote
asked Jul 2, 2014 in WPF by Doreen

I would like to understand the concept of Type converter in WPF. What is the use of a Type converter? Where and why should I use it.

Share

1 Answer

+1 vote
answered Jul 2, 2014 by Nixon
selected Jul 2, 2014 by administrator
 
Best answer

Here is a simple XAML code.

<Button Margin="10,20,10,30" Content="Click me"/>

In the above code, we are specifying string within double quotes as Margin vlaue. So, how does the string is converted to Margin? Here is what happens behind the scene.

Whenever the XAML processor processes an attribute, first it will check the data type of the attribute. For example “Height” attribute’s data type is “int”. Then it will check the value set for that attribute and finds whether it is direct string value or markup extension. If the value is string, then it will try to convert that string to the type of the attribute. In our case, it will convert the string to Integer.

Suppose, If the attribute type is not any primitive type, but enumeration, then the processor will check the value set to that attribute is matched with the item inside the enum. If it is matched, then it will use that.

Next option could be the value set in the attribute may not be primitive or Enum. In that case, XAML processor will look for another thing called “Type Converter”.
Lets look at another example.

<Button Margin="10,20,10,30" Content="Click me"/>

Here Margin is a property of class button. If you see the data type of the Margin property in .NET library, it is “Thickness”

wpf-margin-property-snapshot

But our example sets the value as 4 integer values separated by comma within double quotes. So, the process does not know how to convert this value to “Thickness” type. That where the concept of Type Converter is used.

What you can do is, you can create a converter class which knows how to convert the Margin string value to “Thinkness” type. To do this, you can create a class then derive it from “TypeConverter” class available in .net library. Once you do that, it allows you to override 4 main methods “CanConvertFrom”, “ConvertFrom”, “CanConvertTo”, “ConvertTo”. The name of the methods provide the self explanation.

Once you create your own type converter, then you can use “TypeConverterAttribute” on top of your original Type and pass the type of “TypeConverter” which should be used.
For example, to convert the Margin value to Thickness, on top “Thickness” class you can see TypeConverterAttribute with “ThicknessConverter” passed as argument.

wpf-thickness-typeconverter-snapshot

Your answer

Preview

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
site design / logo / content © 2013 - 2015 pinfaq.com
...