2016-09-21 76 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屬性。