布局:
实际效果:
代码部分:
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 //打开当前按钮对应面板,其他关闭 46 for (int i = 0; i < settingPanels.Count; i++) 47 { 48 Panel panel = settingPanels[i] as Panel; 49 if (i == index) 50 { 51 panel.Visible = !panel.Visible; 52 } 53 else 54 { 55 panel.Visible = false; 56 } 57 } 58 59 }