核心變數與屬性
private string[] _Module;
private int _ModuleButtonWidth = 25;
public string[] Module {
get { return _Module; }
set { _Module = value; }
}
Form_Load:動態建立模組按鈕
private void Form1_Load(object sender, EventArgs e) {
this.panel1.BorderStyle = BorderStyle.None;
Module = new[] { "模組1", "模組2", "模組3", "模組4", "模組5" };
for (int i = 0; i < Module.Length; i++) {
Button btn = new Button {
FlatStyle = FlatStyle.Popup,
Width = _ModuleButtonWidth,
Height = panel1.Height,
Name = "Button" + i,
Text = Module[i],
Left = panel1.Width - _ModuleButtonWidth * (Module.Length - i)
};
btn.Click += btn_Click;
panel1.Controls.Add(btn);
}
}
btn_Click:切換面板與載入 UserControl
private void btn_Click(object sender, EventArgs e) {
bool found = false;
// 移除舊面板
for (int i = 0; i < panel1.Controls.Count; i++) {
if (panel1.Controls[i] is Panel) {
panel1.Controls.RemoveAt(i--);
}
}
// 重新定位按鈕並載入對應面板
for (int i = 0; i < panel1.Controls.Count; i++) {
if (panel1.Controls[i] is Button btn) {
btn.Left = found
? panel1.Width - _ModuleButtonWidth * (Module.Length - i)
: _ModuleButtonWidth * i;
if (btn.Name == ((Button)sender).Name) {
found = true;
Panel p = new Panel {
BackColor = Color.AliceBlue,
Left = _ModuleButtonWidth * (i + 1),
Width = panel1.Width - _ModuleButtonWidth * Module.Length,
Height = panel1.Height
};
switch (i) {
case 0: p.Controls.Add(new ucPart1()); break;
case 1: p.Controls.Add(new ucPart2()); break;
case 2: p.Controls.Add(new ucPart3()); break;
case 3: p.Controls.Add(new ucPart4()); break;
case 4: p.Controls.Add(new ucPart5()); break;
}
panel1.Controls.Add(p);
}
}
}
}
完整原始碼下載
https://files.cnblogs.com/KenBlove/WindowsApplication1.7z