现在的位置: 首页 > 综合 > 正文

C/S WinForm自定义控件实现B/S菜单样式

2012年12月14日 ⁄ 综合 ⁄ 共 2286字 ⁄ 字号 评论关闭

 

思路:

1.      创建项目,添加自定义控件UCTreeView

2.      添加flowLayoutPanel容器控件

3.      添加属性,动态添加菜单连接

4.      Form引用控件

  

// 属性 数据源
public IList<Class1> myClass { get; set; }

 


/// <summary> /// 读取父级菜单栏 /// </summary> private void GetParentData() { foreach (var data in myClass) { if (data.PID == 0) { // 动态生成一个Button,用来显示一级菜单,设置属性 Button btParent = new Button(); btParent.Text = data.Name.ToString(); btParent.Name = data.ID.ToString(); btParent.BackgroundImage = global::TreeView.Properties.Resources.left_nav_bg; btParent.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; btParent.Cursor = System.Windows.Forms.Cursors.Hand; btParent.Dock = System.Windows.Forms.DockStyle.Fill; btParent.FlatAppearance.BorderSize = 0; btParent.FlatStyle = System.Windows.Forms.FlatStyle.Flat; btParent.ForeColor = System.Drawing.Color.White; btParent.Size = new System.Drawing.Size(172, 28); btParent.TabIndex = 0; btParent.UseVisualStyleBackColor = true; btParent.TabIndex = 0; // 将button添加到面板控件中显示 this.flowLayoutPanel1.Controls.Add(btParent); // 根据一级菜单获取二级菜单信息,并显示 AddNode(data.ID); // button点击事件 btParent.Click += new EventHandler(btParent_Click); } } } /// <summary> /// 点击事件,控制二级菜单是否显示 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void btParent_Click(object sender, EventArgs e) { Button btn = sender as Button; if (this.flowLayoutPanel1.Controls.ContainsKey("pl_" + btn.Text)) { Panel pl = this.flowLayoutPanel1.Controls["pl_" + btn.Text] as Panel; // 判断二级菜单是否为显示,如显示则隐藏,如隐藏则关闭 if (pl.Visible == true) pl.Visible = false; else pl.Visible = true; } } /// <summary> /// 二级菜单的填充显示 /// </summary> /// <param name="p">父级ID</param> private void AddNode(int p) { // 二级菜单总容器控件 Panel pl = new Panel(); pl.Name = "pl_" + p; foreach (var data in myClass) { if (data.PID == p) { Button btnChild = new Button(); btnChild.Text = data.Name.ToString(); btnChild.Name = data.ID.ToString(); btnChild.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; btnChild.Cursor = System.Windows.Forms.Cursors.Hand; btnChild.Dock = System.Windows.Forms.DockStyle.Top; btnChild.FlatAppearance.BorderSize = 0; btnChild.FlatStyle = System.Windows.Forms.FlatStyle.Flat; btnChild.ForeColor = System.Drawing.Color.Black; btnChild.Name = "btnChild"; btnChild.Size = new System.Drawing.Size(172, 28); btnChild.TabIndex = 0; btnChild.Text = data.ID.ToString(); btnChild.UseVisualStyleBackColor = true; // 将菜单添加到容器中pl pl.Controls.Add(btnChild); } } // 将动态容器添加到总容器面板中 this.flowLayoutPanel1.Controls.Add(pl); }

 

注:动态创建控件添加,布局规则为:先进为下,后进为上。

 

抱歉!评论已关闭.