2016-09-21 89 views
0

我有一个类可以是英寸或毫米的测量,现在使用expandabletypeconverter它有点烦人的改变测量,所以我想创建一个自定义的。问题是,propertygrid似乎忽略了它。我把断点,但没有任何东西被称为。这里是代码:c#propertygrid与自定义typeconverter,不能输入字符串

[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); 
    } 
} 

我不能在propertygrid中输入一个字符串。它只是显示toString()返回的内容。

回答

0

即时消息并且仍然拥有包含它们的类中属性本身的typeconverter属性。