问题描述
该DateTimeConverter类提供了日期时间和字符串之间的转换。我也想支持DateTime和双之间的转换。
The DateTimeConverter class provides conversions between DateTime and string. I would also like to support conversions between DateTime and double.
根据MSDN我可以扩展DateTimeConverter类来做到这一点 - 看的
According to MSDN I can extend the DateTimeConverter class to do this - see MSDN DateTimeConverter
我创建了一个类继承自DateTimeConverter,并提供相应的替换值CanConvertTo,CanConvertFrom等。
I have created a class that inherits from DateTimeConverter and provides the appropriate overrides for CanConvertTo, CanConvertFrom, etc.
我如何确保该框架使用我的日期时间转换器(DateTimeConverterEx),而不是在BCL(DateTimeConverter)中提供的时候,code以下被称为?
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));
感谢。
推荐答案
您需要分配的转换器。在属性按属性的基础上,你可以使用:
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.
(修改)
要设置转换器的任何 的DateTime
:
TypeDescriptor.AddAttributes(typeof(DateTime),
new TypeConverterAttribute(typeof(DateTimeConverterEx)));
现在你的样品code应该工作。
Now your sample code should work.
这篇关于扩展的TypeConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!