Convert in code as in XAML: how to get the XAML processor’s converter ?

, , 1 Comment

convert featured imageSometimes you need to set property on controls from the code and then you realize that this is not like in XAML: these are not strings? No, they are not! This is because the XAML processor convert the string to the correct type when it process the XAML. In this post we’ll see how to reproduce the same behavior from the code: a little snippet which can help you someday !

As you can find out on MSDN, everything is done trough the class TypeConverter. For any type, you can create a TypeConverter (to be precise: a class inheriting from TypeConverter) which will convert it from any other type and especially string. Note that there is only four methods used in the XAML processing: CanConvertTo, CanConvertFrom, ConvertTo, ConvertFrom.

When the XAML processor process the XAML it checks, the presence of a TypeConverter attribute on the target property. This attribute simply specify which converter can be used to convert a value from a given type to a value of the aimed property’s type. If it exists, the XAML processor instanciates one and use it to convert to the correct type value.

Here is the snippet, in his simplified version, I use to reproduce the same behavior in code:

[csharp]
public T ConvertTo<T>(string originalString)
{
var typeConverter = TypeDescriptor.GetConverter(typeof(T));
if (typeConverter != null)
return (T)typeConverter.ConvertFromString(originalString);
else
{
var errorMsg = string.Format("Cannot retrive the converter of type{0}",
typeof(T).Name);
throw new ArgumentOutOfRangeException(errorMsg);
}
}

public T ConvertTo<T>(object originalValue)
{
var typeConverter = TypeDescriptor.GetConverter(typeof(T));
if (typeConverter != null)
return (T)typeConverter.ConvertFrom(originalValue);
else
{
var errorMsg = string.Format("Cannot retrive the converter of type{0}",
typeof(T).Name);
throw new ArgumentOutOfRangeException(errorMsg);
}
}
[/csharp]

I can then use it to do the most common thing in XAML: create a SolidColorBrush from a string. You can notice that any representation can be used: hexadecimal, name of the color, etc. :

[csharp]SolidColorBrush redBrush = ConvertTo<SolidColorBrush>("Red");
SolidColorBrush anotherBrush = ConvertTo<SolidColorBrush>("#FF125645");
[/csharp]

This is just an exemple and this snippet can be enhanced with, for example, calls to CanConvertXXX. Also if you want more information on TypeConverter and how to implement a custome one, I recommend you to read the MSDN page which is quite well written on this subject.

Regards,

kick it on DotNetKicks.com

 

One Response

Comments are closed.