PropertyGrid-集合版本/包装器



我有一种复杂的属性要在PropertyGrid中编辑。

interface IInterface{}
abstract class Base : IInterface{}
class A : Base{}
class B : Base{}

这些类表示可以存储在属性中的内容(这些类的内容无关紧要)。

// The Property to be displayed in the PropertyGrid
class Property
{
    List<Base> MyListOfObjects {get;set;}        
}

我设法创建了一个System.ComponentModel.Design.CollectionEditor的派生类,它允许我使用collection属性中的[Editor(typeof(MyCollectionEditor), typeof(UITypeEditor))]属性添加不同类型的数据。

class MyCollectionEditor : CollectionEditor
{
    public MyCollectionEditor(Type type) : base(type)
    {            
    }
    #region Overrides of CollectionEditor
    protected override Type[] CreateNewItemTypes()
    {
        base.CreateNewItemTypes();
        // [EDIT assembly, see below]
        var types = (from t in Assembly.GetAssembly(typeof(IInterface)).GetTypes()
                     where t.GetInterfaces().Contains(typeof (IInterface)) && !t.IsAbstract
                     select t).ToArray();
        return types;
    }
    protected override Type CreateCollectionItemType()
    {
        return typeof(A); // 1st problem
    }
}
  • 第一个问题:我发现能够编辑对象的唯一解决方案是在CreateCollectionItemType()中给出一个具体的子类类型。为什么?如何避免这种情况?

  • 第二个问题:我现在想使用包装器将此属性赋予propertyGrid项。我不想在模型中有属性属性(例如[Category("General")]),而是想把它们放在包装器中。

它适用于除系列以外的所有产品。以下是我的做法:

class abstract WrapperBase<T>
{
    T WrappedObject{get;set;}
}
class PropertyWrapper:WrapperBase<Property>
{
    List<Base> MyListOfObjects
    {
        get{return WrappedObject.MyListOfObjects;}
        set{WrappedObject.MyListOfObjects=value;}
    }
}

这样,集合编辑器就不允许我向该集合添加对象,并且可用于添加特定类型对象的下拉列表也不见了。

知道吗?提前感谢!


[EDIT]

问题的第二部分得到了解决:由于包装器位于另一个程序集中,我没有找到IInterface实现的正确位置。

CreateNewItemTypes很好。在CreateCollectionItemType中返回基类型。我认为这应该行得通。

最新更新