Nullable TypeConverter for Silverlight

In Silverlight if you want a property of one of your Controls or Models to be Nullable<T> you will end up with a parser error without a little extra work. The reason for this is that there is no default TypeConverter for Nullable<T> so the parser doesn’t know how to convert the string in the Xaml to the appropriate type. To fix this you simply create your own TypeConverter and apply it to your property.

public class NullableTypeConverter<T> : TypeConverter
    where T : struct
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(string);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        Nullable<T> nullableValue = null;
        string stringValue = value as string;
        if (!string.IsNullOrEmpty(stringValue))
        {
            T converted = (T)Convert.ChangeType(value, typeof(T), culture);
            nullableValue = new Nullable<T>(converted);
        }

        return nullableValue;
    }
}

Then to apply it you simply do the following:

[TypeConverter(typeof(NullableTypeConverter<int>))]
public int? Example { get; set; }

Author: justinmchase

I'm a Software Developer from Minnesota.

Drop a brain bomb

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s