How to make a UserControl with a Collection that c

2019-06-13 17:23发布

I'm making a class called PanelsList that is basically a TabControl without the headers on the top, so the pages can only be changed programmatically. Each "tab" will be and instance of a class called PanelsListItem that derives from Panel. I also made a class PanelsListItemCollection that implements ICollection and ICollection<PanelsListItem>. So I added the following to my PanelsList:

    private PanelsListItemCollection _Items;

    public PanelsListItemCollection Items
    {
        get { return _Items; }
        set { SetItems(value); }
    }

    private void SetItems(PanelsListItemCollection value)
    {
        if (_Items != value)
        {
            if (_Items != null) _Items.PanelsList= null;
            _Items = value;
            if (_Items != null) _Items.PanelsList= this;
        }
    }

I assumed that after building and adding a PanelsList to my form I would be able to edit the PanelsListItemCollection on design time. But when I click on the "..." button on the property Items in the Proeprties editor, the Object Collection Editor opens but the Add and Remove buttons are disabled.

When I added a property List<Control> Stuff { get; set; } to my PanelsList I could add and remove controls from Stuff on design time. I wonder if I need to implement IList instead of ICollection?

Edit: I just tried implementing also IList<PanelsListItem> but it didn't fix it.

1条回答
我命由我不由天
2楼-- · 2019-06-13 17:23

In order for a collection to be automatically supported by the designer, it must implement the non-generic IList interface - IList<T> will not automatically work. This is because the default collection editor relies on knowing the index of each item. The other requirement for compatibility with the designer (which your code already satisfies) is that the property exposing your collection must have both get and set methods; the designer makes a temporary copy of your collection during editing and then assigns it to the property when the user clicks OK.

If the default is not good enough, you can implement your own collection editor by extending the UITypeEditor class (in the System.Drawing.Design namespace) and decorating the property in your code with the EditorAttribute, e.g.

[Editor(typeof(MyCustomCollectionEditor), typeof(UITypeEditor))] 
public PanelsListItemCollection Items { /* ... */ }

You can also extend the existing CollectionEditor class, but the class only exposes very limited functionality to derived classes.

查看更多
登录 后发表回答