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:

public int? Example { get; set; }

Author: justinmchase

I'm a Software Developer from Minnesota.

Leave a Reply

%d bloggers like this: