在一个主窗口中,有一个panel,点击树形结构的节点,在panel中显示窗口
using System;
using System.Collections;
using System.Text;
using System.Reflection;
namespace MengYe
{
/// <summary>
/// 导入的类
/// </summary>
class InstanceFactory
{
private static Hashtable ServiceList = new Hashtable();
/// <summary>
/// 使用反射生成指定的服务对象,将调用服务类的默认构造函数。
/// </summary>
/// <param name="serviceType"></param>
/// <returns></returns>
public static Object CreateInstance(Type type)
{
if (type == null)
return null;
if (ServiceList.Contains(type)) return ServiceList[type];
ConstructorInfo constor = type.GetConstructor(Type.EmptyTypes);
Object obj = constor.Invoke(new Object[0]);
ServiceList.Add(type, obj);
return obj;
}
/// <summary>
/// 根据指定构造函数的参数数组,调用相应的构造函数生成对象。
/// </summary>
/// <param name="type">类型</param>
/// <param name="args">构造参数数组</param>
/// <returns></returns>
public static Object CreateInstance(Type type, Object[] args)
{
if (type == null) return null;
//如果构造参数列表为空或长度为0,将转为默认构造函数生成对象。
if (args == null || args.Length == 0)
{
return CreateInstance(type);
}
Type[] types = new Type[args.Length];
//获取构造函数数组的类型
for (int i = 0; i < args.Length; i++)
{
types[i] = args[i].GetType();
}
ConstructorInfo constor = type.GetConstructor(types);
if (constor != null)
{
try
{
return constor.Invoke(args);
}
catch { }
}
return null;
}
public static Object CreateInstance(String className)
{
return CreateInstance(Type.GetType(className, true));
}
public static Object CreateInstance(String className, Object[] args)
{
return CreateInstance(Type.GetType(className, true), args);
}
}
}
在主窗口中写:
/// <summary>
/// 树形节点的点击事件
/// </summary>
/// <param name="obj"></param>
/// <param name="e"></param>
private void Tv_userpower_Select(object obj, TreeViewEventArgs e)
{
TreeNode selectnode = e.Node;
if (selectnode.Name.ToString ().Trim().Length > 0)
{
string classString = selectnode.Name.ToString();
string powername = selectnode.Text.ToString();
this.lab_model.Text = "当前所在位置:" + powername;
AddPanel(classString);
}
}
/// <summary>
/// 显示窗口到选项卡中
/// </summary>
/// <param name="classString">窗口的名字</param>
private void AddPanel(string classString)
{
this.panel_form.Controls.Clear();
//传进去一个大panel用于装用户建的panel
Object o = InstanceFactory.CreateInstance(classString, new Object[1] { this.panel_form});
UserControl frm = o as UserControl;
}
要显示的窗口修改为:
public partial class Employee : UserControl
{
public Employee(Control container)
{
container.SuspendLayout();
InitializeComponent();
this.Dock = DockStyle.Fill;
container.Controls.Add(this);
container.ResumeLayout(false);
container.PerformLayout();
}
}