tags:

views:

49

answers:

1

I have a project that has a user interface that consists of two panels (left & right).

In the left hand panel is a treeview. Depending on the node selected a different "form" is required in the right hand panel.

So far I have defined, a bunch of different "User controls" for the right hand panel and I create them and show them as required by the right node being selected from the treeview.

Is there a "pattern" for managing this sort of process as my code ( too long to include here ) is very brittle and not at all extensible. Anyone got any suggestions or even know of an open source project that achieves the same kind of thing.

+4  A: 

This doesn't have to be difficult. Dock a TreeView on the left, add a panel and set its Dock to Fill. Then use code like this to select a user control into it:

    private UserControl currentView;

    public void SelectView(UserControl ctl) {
        if (currentView != null) {
            panel1.Controls.Remove(currentView);
            currentView.Dispose();
        }
        if (ctl != null) {
            ctl.Dock = DockStyle.Fill;
            panel1.Controls.Add(ctl);
        }
        currentView = ctl;
    }

You can get fancy on the TreeView by using reflection. In the designer, set the node's Name property to the name of the user control (like "UserControl1"). And implement the BeforeSelect event similar to this:

    private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e) {
        string name = e.Node.Name;
        name = this.GetType().Namespace + "." + name;
        Type ctlType = System.Reflection.Assembly.GetExecutingAssembly().GetType(name);
        if (ctlType == null) e.Cancel = true;
        else {
            var ctor = ctlType.GetConstructor(new Type[] { });
            var ctl = ctor.Invoke(null) as UserControl;
            SelectView(ctl);
        }
    }

That's all. Tweak the above code if the user controls are in a different namespace or in a different assembly.

Hans Passant
+1: Rather than using the `Name` property and reflection, how about setting the `Tag` property to a `Func<Control>`?
Alex Humphrey
@Alex: yes there are many ways to go. I was trying to avoid the boilerplate code you'd need to get everything initialized.
Hans Passant