【发布时间】:2016-09-21 21:59:30
【问题描述】:
我有一个可以以英寸或毫米为单位的测量类,现在使用可扩展类型转换器更改测量有点烦人,所以我想创建一个自定义的。问题是,propertygrid 似乎忽略了它。我放了断点,但什么都没有被调用。这是代码:
[TypeConverter(typeof(MeasurementConverter))]
public class Measurement
{
double mm;
public bool IsMM
{
get; set;
}
public double Inches
{
get { return mm / 25.4; }
set { mm = value * 25.4; IsMM = false; }
}
public double Millimeters
{
get { return mm; }
set { mm = value; IsMM = true; }
}
public Measurement(double value = 0, bool ismm = true)
{
if(ismm)
{
Millimeters = value;
}
else
{
Inches = value;
}
}
public override string ToString()
{
if(IsMM)
{
return Millimeters.ToString(SVGElement.doubleFormat) + "mm";
}
else
{
return Inches.ToString(SVGElement.doubleFormat) + "in";
}
}
}
public class MeasurementConverter : TypeConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return typeof(string) == destinationType;
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if(destinationType == typeof(string))
{
Measurement m = value as Measurement;
return m.ToString();
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return typeof(string) == sourceType;
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
string str = value as string;
if(str != null)
{
var tmp = context.Instance;
Measurement m = new Measurement();
if(str.EndsWith("mm"))
{
m.Millimeters = double.Parse(str.Substring(0, str.Length - 2));
}
else if(str.EndsWith("in"))
{
m.Inches = double.Parse(str.Substring(0, str.Length - 2));
}
else //assume mm
{
try
{
m.Millimeters = double.Parse(str);
}
catch { }
}
return m;
}
return base.ConvertFrom(context, culture, value);
}
}
我无法在属性网格中输入字符串。它只是显示 toString() 返回的内容。
【问题讨论】:
标签: c# propertygrid typeconverter