0

I have a custom control derived from ListView (say MyListView). In the designer mode I define several ListViewGroups in it. Unfortunately, if I later use this control on a form, whenever I open the designer for this form, it adds the same set of groups to the MyListView control. So after some editing there is a big number of duplicate groups in it.

It seems the form designer (not surprisingly) cannot recognize that the groups were already added in the MyListView constructor and not in the form itself, so it should not add the code to generate them in InitializeComponent(). Can I prevent this somehow?

4

1 回答 1

0

This is because you added the groups in the constructor, which also runs at design time, and their values are getting saved in the form's Designer.cs file. The constructor runs too early so you cannot see what groups will be added, later, by InitializeComponent(). And it runs too early to get a reliable indication that the code runs in design mode, the DesignMode property is still false.

The proper fix is to give the control its own designer but that is very painful, especially so for ListView. The cheap workaround is to postpone adding the groups and using an event that runs after InitializeComponent. The HandleCreated event is good for that. Like this:

class MyListView : ListView {
    protected override void OnHandleCreated(EventArgs e) {
        base.OnHandleCreated(e);
        if (this.DesignTime && this.Groups.Count == 0) {
            // Add the groups here
            //...
        }
    }
}
于 2012-11-20T15:39:44.670 回答