C# Winform 動態添加菜單 (轉)


最近在做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();

        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM