CollectionEditor中的集合无法转换为项目

时间:2017-05-02 11:56:16

标签: c# windows winforms

我已经创建了自定义集合和自定义集合编辑器,用于在Windows窗体应用程序的设计器级别编辑集合。

但是,当我单击集合编辑器的“添加”按钮时,该值将作为集合本身而不是“项目”进行检索。

以下是我的代码部分:

public MyItem 
{
 .....
}

[EditorAttribute(typeof(MyItemCollectionEditor), typeof(UITypeEditor))]
[TypeConverter(typeof(MyItemCollectionConverter))]
public MyItemCollection : : ICollection, IDisposable, ICloneable, IList, ICustomTypeDescriptor
{

     //implemented all the interfaces.

     int IList.Add(object value)
     {
         Add((MyItem)value);  //Exception thrown as "could not convert type of MyItemCollection to MyItem"

         //Why itemcollection coming as value instead of item.
     }

}



public class MyItemCollectionEditor : CollectionEditor
{
    public MyCollectionEditor(Type type)
        : base(type)
    {
    }

    protected override Type CreateCollectionItemType()
    {
        return typeof(MyItemCollection);
    }

    protected override bool CanSelectMultipleInstances()
    {
        return false;
    }

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        return base.EditValue(context, provider, value);
    }
}


public class MyItemCollectionConverter : ExpandableObjectConverter
{

    public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
    {
        return ((ICustomTypeDescriptor)value).GetProperties(attributes);
    }

    public override bool GetPropertiesSupported(ITypeDescriptorContext context)
    {
        return context == null || context.PropertyDescriptor == null
        || (context.Instance != null && GetCount(context.PropertyDescriptor.GetValue(context.Instance)) > 0);
    }

    public override /*TypeConverter*/ bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        if (destinationType == typeof(string))
        {
            return true;
        }
        else
        {
            return base.CanConvertTo(context, destinationType);
        }
    }

    int GetCount(object value)
    {
        if (value == null)
        {
            return 0;
        }

        return ((ICustomTypeDescriptor)value).GetProperties(null).Count;
    }

    public override /*TypeConverter*/ object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string))
        {
            int count = GetCount(value);
            return count > 0 ? String.Format("Count = {0}", count) : string.Empty;
        }

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

有谁可以让我知道,为什么物品收藏来添加而不是项目?

1 个答案:

答案 0 :(得分:0)

我认为您的错误可能是此方法的实施:

protected override Type CreateCollectionItemType()
{
    return typeof(MyItemCollection);
}

这应该是

protected override Type CreateCollectionItemType()
{
    return typeof(MyItem);
}

请参阅documentation in MSDN