views:

278

answers:

1

The DateTimeConverter class provides conversions between DateTime and string. I would also like to support conversions between DateTime and double.

According to MSDN I can extend the DateTimeConverter class to do this - see MSDN DateTimeConverter

I have created a class that inherits from DateTimeConverter and provides the appropriate overrides for CanConvertTo, CanConvertFrom, etc.

How do I make sure that the framework uses my DateTime converter (DateTimeConverterEx) instead of the one provided in the BCL (DateTimeConverter) when the code below is called?

    DateTime dt = DateTime.Now;
    // This line returns a DateTimeConverter which I don't want. 
    // Would like to get a DateTimeConverterEx.
    TypeConverter tc = TypeDescriptor.GetConverter(dt);
    double dbl = (double)tc.ConvertTo(dt, typeof(double));

Thanks.

+2  A: 

You need to allocate the converter. On a property-by-property basis, you can use:

[TypeConverter(typeof(DateTimeConverterEx))]
public DateTime Foo {get {...} set {...}}

This would then work for usage of the form:

var prop = TypeDescriptor.GetProperties(obj)["Foo"];
var converter = prop.Converter;
// as before, using "converter"

This will work for most common binding scenarios.

(edit)

To set the converter for any DateTime:

TypeDescriptor.AddAttributes(typeof(DateTime),
    new TypeConverterAttribute(typeof(DateTimeConverterEx)));

Now your sample code should work.

Marc Gravell