在一個主窗口中,有一個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();
}
}