c# WinForm Menu自动生成
1.将采用递归的方式生成窗体菜单,并且添加其事件响应
Type t = typeof(frmMain); private void GenerateMenu(ToolStripItemCollection parentItem, List<SpinSystem.Domain.Main.Menu> menus,string paentId) { object o = this; if (menus == null) return; List<SpinSystem.Domain.Main.Menu> currentMenus = menus.Where(n => n.PARENT_ID == paentId).ToList(); ToolStripMenuItem item = null; for (int i = 0; i < currentMenus.Count; i++) { if (!currentMenus[i].MENU_NAME.ToUpper().Equals("LINE")) { item = new ToolStripMenuItem(currentMenus[i].MENU_DISPLAY); item.Name = currentMenus[i].MENU_NAME; MethodInfo info = t.GetMethod(currentMenus[i].LINK_FUNC); if (info != null) { Delegate del = Delegate.CreateDelegate(typeof(EventHandler), o, info); EventHandler myMethod = del as EventHandler; item.Click += myMethod; } parentItem.Add(item); } else { ToolStripSeparator line = new ToolStripSeparator(); parentItem.Add(line); continue; } GenerateMenu(item.DropDownItems, menus, currentMenus[i].MENU_ID); } }
2.调用代码
List<SpinSystem.Domain.Main.Menu> menus = services.GetMenuListByUserId(SpinSystem.Domain.Login.LoginUsercs.LoginUser.UserId); this.mnsMain.Items.Clear(); GenerateMenu(this.mnsMain.Items,menus,"0");