I have designed a custom type :
public abstract class Numeric
{
private decimal value;
public Numeric(decimal value)
{
this.value = value;
}
public decimal Value
{
get { return value; }
}
public virtual uint Size
{
get { return 5; }
}
public virtual uint Precision
{
get { return 2; }
}
public override string ToString()
{
return value.ToString();
}
}
[TypeConverter(typeof(NumericTypeConverter<Quantity>))]
public class Quantity : Numeric
{
public static implicit operator Quantity(decimal input)
{
return new Quantity(input);
}
public static implicit operator decimal(Quantity input)
{
return input.Value;
}
public Quantity(decimal value) : base(value) { }
public override uint Precision
{
get { return 0; }
}
}
I then went on to create a TypeConverter :
public class NumericTypeConverter<typeT> : TypeConverter where typeT :
Numeric
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type
sourceType)
{
return sourceType == typeof(string) ? true :
base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
// use LCG to call constructor of typeT with value as parameter
}
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type
destinationType)
{
return destinationType == typeof(string) ? true :
base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
// use LCG to call constructor of typeT with value as parameter
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture, object value, Type
destinationType)
{
if (destinationType == typeof(string))
return (value as INumericType).Value.ToString();
return base.ConvertTo(context, culture, value, destinationType);
}
}
On a form, I create an instance of a class with a Quantity property, and add
a Binding to a TextBox control :
public class Test
{
private Quantity price;
public Quantity Price
{
get { return price; }
set { price = value; }
}
}
{
Test test = new Test();
test.Price = 12.34M;
Binding b = new Binding("Text", test, "Price");
textBox1.DataBindings.Add(b);
}
When I edit the value from its original 12.34 and then exit the TextBox, the
ConvertTo method of the type converter is called and the value in the
TextBox reverts to 12.34 !!!
Why is it that the CanConvertTo and ConvertTo methods of the type converter
get called, but not the CanConvertFrom and ConvertFrom methods don't ??
Joanna
--
Joanna Carter [TeamB]
Consultant Software Engineer