最近在做WINFORM開發,一直都在為主界面的點擊事件及動態加載菜單苦腦。現在已解決這個問題了,可以實現數據庫或都XML等配置完成動態生成菜單及事件加載。代碼如下:
private void Form1_Load(object sender, EventArgs e)
{
//添加菜單一
ToolStripMenuItem subItem;
subItem = AddContextMenu("入庫", menuStrip1.Items, null);
//添加子菜單
AddContextMenu("添加入庫", subItem.DropDownItems, new EventHandler(MenuClicked));
AddContextMenu("入庫管理", subItem.DropDownItems, new EventHandler(MenuClicked));
//添加菜單二
subItem = AddContextMenu("出庫", menuStrip1.Items, null);
//添加子菜單
AddContextMenu("添加出庫", subItem.DropDownItems, new EventHandler(MenuClicked));
AddContextMenu("出庫管理", subItem.DropDownItems, new EventHandler(MenuClicked));
}
/// <summary>
/// 添加子菜單
/// </summary>
/// <param name="text">要顯示的文字,如果為 - 則顯示為分割線</param>
/// <param name="cms">要添加到的子菜單集合</param>
/// <param name="callback">點擊時觸發的事件</param>
/// <returns>生成的子菜單,如果為分隔條則返回null</returns>
ToolStripMenuItem AddContextMenu(string text, ToolStripItemCollection cms, EventHandler callback)
{
if (text == "-")
{
ToolStripSeparator tsp = new ToolStripSeparator();
cms.Add(tsp);
return null;
}
else if (!string.IsNullOrEmpty(text))
{
ToolStripMenuItem tsmi = new ToolStripMenuItem(text);
tsmi.Tag = text + "TAG";
if (callback != null) tsmi.Click += callback;
cms.Add(tsmi);
return tsmi;
}
return null;
}
void MenuClicked(object sender, EventArgs e)
{
//以下主要是動態生成事件並打開窗體
//((sender as ToolStripMenuItem).Tag)強制轉換
ObjectHandle t = Activator.CreateInstance("WinForms", "WinForms.Form2");
Form f = (Form)t.Unwrap();
f.ShowDialog();
}