开发者

Treeview to control panels

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜