6

我有一堂课:

public class Filter
{
    public Filter (string name, string value)
    {
        Name = name;
        Value = value;
    }

    public string Name {get; private set;}
    public string Value {get; set;}
}

还有一个集合类:

public class FilterCollection : Collection<Filter>
{
   // code elided
}

我的组件类:

public class MyComponent : Component
{
    // ...

    [Editor(typeof(FilterEditor), typeof(UITypeEditor))]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public FilterCollection Filters { get; set; }

    // ...
}

问题是设计者没有正确序列化集合。

我确定我错过了一些东西,但我不知道是什么。

附加信息

我希望 Designer.cs 文件具有以下内容:

myComponent.Filters.Add (new Filter ("some name", "some value"));
myComponent.Filters.Add (new Filter ("other name", "other value"));

这可行吗?

4

1 回答 1

3

好的,问题解决了。

我需要为我的Filter类使用TypeConverter :

internal class FilterConverter : TypeConverter
{
    public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
    {
        return destinationType == typeof(InstanceDescriptor) || base.CanConvertTo (context, destinationType);
    }

    public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(InstanceDescriptor) && value is Filter)
        {
            ConstructorInfo constructor = typeof (Filter).GetConstructor (new[] {typeof (string), typeof (string)});

            var filter = value as Filter;
            var descriptor = new InstanceDescriptor (constructor, new[] {filter.Name, filter.Value}, true);

            return descriptor;
        }
        return base.ConvertTo (context, culture, value, destinationType);
    }
}

然后将转换器添加到Filter类中,如下所示:

[TypeConverter(typeof(FilterConverter))]
public class Filter
{
    // ...
}

这里要注意的重要一点是使用Filter构造函数所需的参数创建实例描述符。此外,您需要将InstanceDescriptor构造函数的最后一个参数 ( isComplete )设置为true

于 2012-05-02T20:35:24.787 回答