Item Collection option for a User Control

2020-02-11 07:09发布

As you can see in the pic below, for a ListView Control you can add Items using the Properties pane.

How do I enable this kind of stuff for my UserControl?

I'm not getting anything when I search Google, but I'm probably not using the correct terms.

Does anybody know?

Thanks

Visual Studio Properties Pane

1条回答
疯言疯语
2楼-- · 2020-02-11 08:00

You need to create a class that defines the object type that the collection ids composed of. A listView has ListViewItem objects. A TabControl has TabPage objects. Your control has objects which are defined by you. Let's call it MyItemType.

You also need a wraper class for the collection. A simple implementation is shown below.

public class MyItemTypeCollection : CollectionBase
{

    public MyItemType this[int Index]
    {
        get
        {
            return (MyItemType)List[Index];
        }
    }

    public bool Contains(MyItemType itemType)
    {
        return List.Contains(itemType);
    }

    public int Add(MyItemType itemType)
    {
        return List.Add(itemType);
    }

    public void Remove(MyItemType itemType)
    {
        List.Remove(itemType);
    }

    public void Insert(int index, MyItemType itemType)
    {
        List.Insert(index, itemType);
    }

    public int IndexOf(MyItemType itemType)
    {
       return List.IndexOf(itemType);
    }
}

Finally you need to add a member variable for the collection to your user control and decorate it properly:

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public MyItemTypeCollection MyItemTypes
    {
        get { return _myItemTypeCollection; }
    }

and you now have a simple interface that allows you to browse and edit the collection. Leaves a lot to be desired still but to do more you will have to learn about custom designers which can be difficult to understand and implement.

查看更多
登录 后发表回答