其他分享
首页 > 其他分享> > 带有继承类的属性列表的PropertyGrid编辑器

带有继承类的属性列表的PropertyGrid编辑器

作者:互联网

我正在寻找类似以下内容的属性编辑器示例:

public class ContainerClass
{
  public string ContainerName { get; set; }
  public List<ContainerBase> Containers { get; set; }

  public ContainerClasss()
  {
    Containers = new List<ContainerBase>();
  }
}

public class ContainerBase
{
  public string Name { get; set; }
  public string Description { get; set; }
  public string Material { get; set; }
  public float Area { get; set; }
}

public class Bookbag : ContainerBase
{
  public int Pockets { get; set; }

  public Bookbag()
  {
    Description = "Bookbag";
  }
}

public class Bookcase : ContainerBase
{
  public Color Color { get; set; }
  public int Shelves { get; set; }

  public Bookcase()
  {
    Description = "Bookcase";
  }   
}

当我单击容器的[…]按钮时,[ADD]按钮允许我添加不同类型的容器,而不是基本容器类…

解决方法:

您可以使用自定义UITypeEditor属性来实现:

public class ContainerClass
{
    ...
    [Editor(typeof(MyCollectionEditor), typeof(UITypeEditor))]
    public List<ContainerBase> Containers { get; set; }
    ...
}

使用此UITypeEditor:

public sealed class MyCollectionEditor : CollectionEditor // need a reference to System.Design.dll
{
    public MyCollectionEditor(Type type)
        : base(type)
    {
    }

    protected override Type[] CreateNewItemTypes()
    {
        return new[] { typeof(ContainerBase), typeof(Bookbag), typeof(Bookcase) };
    }
}

这是它的外观:

标签:propertygrid,propertyeditor,c
来源: https://codeday.me/bug/20191030/1969018.html