This is a mirror of official site: http://jasper-net.blogspot.com/

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

| Sunday, September 4, 2011
Sometimes 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:

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);
    }
}


Read more: Yet Another Blog About…
QR: https://chart.googleapis.com/chart?chs=80x80&cht=qr&choe=UTF-8&chl=http://www.jonathanantoine.com/2011/09/02/convert-in-code-as-in-xaml-how-to-get-thet-xaml-processors-converter/

Posted via email from Jasper-net

0 comments: