views:

22

answers:

0

I have a Panel I want to fill with some UserControl(s) at runtime. These controls are complex and may be interdependent, so I'd like them:

  • to be editable with Visual Studio designer;
  • to be in the same context (= defined in the same class);

Both of the requirements are a must-have.

Considering UserControl is itself an indexed collection of Control(s), I started designing my controls in the same class, without caring about real positioning of them (that will be specified runtime). I already used the same identical approach with DevComponents ribbon containers (with much satisfaction), so I initially thought the same was possible with standard UserControl(s).

I eventually realized that a Control can be inside only one Control.ControlCollection instance at a time, so I couldn't use the Controls property and add controls to another panel without removing them from the original "dummy" UserControl.

My question is: is there a clean and supported way to create this designer-aware UserControl collection? I would call this approach a pattern because it really adds code clearness and efficiency.

Thanks, Francesco

P.S.: as a workaround, I created a DummyControlContainer class that inherits UserControl and keeps a Dictionary map filled at ControlAdded event (code follows). Wondering if there's something cleaner.

public partial class DummyControlContainer : UserControl
{
    private Dictionary<string, Control> _ControlMap;

    public DummyControlContainer()
    {
        InitializeComponent();

        _ControlMap = new Dictionary<string, Control>();
        this.ControlAdded += new ControlEventHandler(DummyControlCollection_ControlAdded);
    }

    void DummyControlCollection_ControlAdded(object sender, ControlEventArgs args)
    {
        _ControlMap.Add(args.Control.Name, args.Control);
    }

    public Control this[string name]
    {
        get { return _ControlMap[name]; }
    }
}