propertygrid中的TypeConverter只能从字符串转换而不是转换为

Rob*_*ssa 5 .net c# propertygrid typeconverter

访问propertygrid时,只会调用ConvertTo方法(很多次).这正确地返回了"Foo!" propertygrid中的字符串.当我点击编辑时,我得到一个例外Cannot convert object of type Foo to type System.String.(不完全,翻译).ConvertFrom方法没有被调用,任何线索为什么?并且错误表明它正在尝试转换为字符串,而不是来自.

我想当我想编辑这个对象时,它必须从Foo转换为字符串,并在完成编辑后.

StringConverter类:

public class FooTypeConverter : StringConverter {
    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
        return new Foo((string) value);
    }

    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
        return "Foo!";
    }

    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
        return true;
    }

    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

正在访问的财产:

Foo _foo = new Foo();
[Editor(typeof(System.ComponentModel.Design.MultilineStringEditor), typeof(UITypeEditor))]
[TypeConverter(typeof(FooTypeConverter))]
public Foo Foo {
    get {
        return _foo;
    }
    set {
        _foo = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

重新更新; 这是一个FooEditor应该作为一个垫片:

class FooEditor : UITypeEditor
{
    MultilineStringEditor ed = new MultilineStringEditor();
    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        Foo foo = value as Foo;
        if (foo != null)
        {
            value = new Foo((string)ed.EditValue(provider, foo.Value));
        }
        return value;        
    }
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
        return ed.GetEditStyle();
    }
    public override bool  IsDropDownResizable {
        get { return ed.IsDropDownResizable; }
    }
}
Run Code Online (Sandbox Code Playgroud)

你显然需要关联它:

[TypeConverter(typeof(FooTypeConverter))]
[Editor(typeof(FooEditor), typeof(UITypeEditor))]
class Foo { /* ... */ }
Run Code Online (Sandbox Code Playgroud)