winform折叠菜单

布局:

实际效果:

代码部分:

 1 private static int showPanelCount = 2; //需要展示的面板数量
 2 private List<Control> settingPanels;
 3 
 4 public DpRight()
 5 {
 6     InitializeComponent();
 7 }
 8 
 9 private void DpLeft_Load(object sender, EventArgs e)
10 {
11 
12     //侧边栏折叠按钮事件
13     settingPanels = new List<Control>();
14 
15     var cons = this.SettingPanel.Controls;
16     for (int i = cons.Count - 1, j = 0; i >= 0; i--)
17     {
18         var con = cons[i];
19 
20         if (con is Button)
21         {
22             con.MouseClick += Button_MouseClick;
23             con.Tag = $"{j}";
24 
25             j++;
26         }
27         else if (con is Panel)
28         {
29             if (j <= showPanelCount)
30                 con.Visible = true;
31             else
32                 con.Visible = false;
33 
34             settingPanels.Add(con);
35         }
36     }
37 
38 }
39 
40 private void Button_MouseClick(object sender, MouseEventArgs e)
41 {
42     Button btn = sender as Button;
43     int index = Convert.ToInt32(btn.Tag.ToString());
44 
45     if (index < settingPanels.Count)
46     {
47         Panel panel = settingPanels[index] as Panel;
48         panel.Visible = !panel.Visible;
49     }
50     else
51     {
52         Console.WriteLine("请添加面板");
53     }
54 
55 }

猜你喜欢

转载自www.cnblogs.com/eliza209/p/12585953.html