c# - propertygrid 中的 TypeConverter 只能从字符串转换,不能转换为

标签 c# .net propertygrid typeconverter

在访问属性网格时,只有 ConvertTo 方法被调用(很多次)。这正确地返回了“Foo!”属性网格中的字符串。当我单击编辑时出现异常 Cannot convert object of type Foo to type System.String.(不完全是翻译)。 ConvertFrom 方法没有被调用,任何线索为什么?错误表明它正在尝试转换为字符串,而不是来自。

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

字符串转换器类:

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

正在访问的属性:

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

最佳答案

回复您的更新;这里有一个 FooEditor 应该可以作为 shim:

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

你显然需要关联它:

[TypeConverter(typeof(FooTypeConverter))]
[Editor(typeof(FooEditor), typeof(UITypeEditor))]
class Foo { /* ... */ }

关于c# - propertygrid 中的 TypeConverter 只能从字符串转换,不能转换为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2116920/

相关文章:

c# - 使属性在 DataGridView 中可见但在 PropertyGrid 中不可见?

c# - 使用不带套接字的 TLS

c# - DDD,聚合根和实体

.net - 哪些 GPS 加密狗适用于 Windows 7 和 .Net 4.0 System.Device.Location 命名空间?

c# - .Net PropertyGrid DropDownList - 返回值不同于显示值

c# - 在运行时创建/修改枚举

c# - 附加和更新有什么区别?

c# - 什么时候应该使用每个线程同步对象?

c# - MVVM WPF 保存和加载用户设置设计模式

c# - 访问从java到dotnet的请求