像做QQ面板一樣,我先定義一些必要的變量和屬性:
private string[] _Module;
private int _ModuleButtonWidth = 25;
/// <summary>
/// 初始模塊
/// </summary>
public string[] Module
{
get { return _Module; }
set { _Module = value; }
}
定義好變量,我們開始寫Form1_Load函數:
private void Form1_Load(object sender, EventArgs e)
{
this.panel1.BorderStyle = BorderStyle.None;
//初始化
Module = new string[] { "初始模塊1", "初始模塊2", "初始模塊3", "初始模塊4", "初始模塊5" };
for (int i = 0; i < Module.Length; i++)
{
//增加模塊Button
Button btn = new Button();
btn.FlatStyle = FlatStyle.Popup;
btn.Width = _ModuleButtonWidth;
btn.Height = this.panel1.Height;
btn.Name = string.Format("Button{0}", i.ToString());
btn.Text = Module[i];
btn.Left = this.panel1.Width - _ModuleButtonWidth * (Module.Length - i);
btn.Click += new EventHandler(btn_Click);
this.panel1.Controls.Add(btn);
}
}
就是將Button加到Panel中,很簡單!下邊開始寫點擊Button加載usercontrol的操作:
private void btn_Click(object sender, EventArgs e)
{
//標志是否找到用戶點擊的Button
bool findOutStatus = false;
//清除上一次操作加載的子菜單項
for (int i = 0; i < this.panel1.Controls.Count; i++)
{
if (this.panel1.Controls[i].GetType().Name == "Panel")
{
this.panel1.Controls.RemoveAt(i);
}
}
for (int i = 0; i < this.panel1.Controls.Count; i++)
{
if (this.panel1.Controls[i].GetType().Name == "Button")
{
//重新定義各個button位置
if (!findOutStatus)
{
this.panel1.Controls[i].Left = _ModuleButtonWidth * i;
}
else
{
this.panel1.Controls[i].Left = this.panel1.Width - _ModuleButtonWidth * (Module.Length - i);
}
//找到所點擊的Button,在其下加載子項
if (this.panel1.Controls[i].Name == ((Button)sender).Name)
{
findOutStatus = true;
Panel panel = new Panel();
panel.BackColor = Color.AliceBlue;
panel.Left = _ModuleButtonWidth * (i + 1);
panel.Width = this.panel1.Width - _ModuleButtonWidth * Module.Length;
panel.Height = this.panel1.Height;
switch (i)
{
case 0:
panel.Controls.Add(new ucPart1());
break;
case 1:
panel.Controls.Add(new ucPart2());
break;
case 2:
panel.Controls.Add(new ucPart3());
break;
case 3:
panel.Controls.Add(new ucPart4());
break;
case 4:
panel.Controls.Add(new ucPart5());
break;
}
this.panel1.Controls.Add(panel);
}
}
}
}
大概意思代碼裡面都有說了..怎麼樣?很簡單吧?!
附完整源代碼:http://files.cnblogs.com/KenBlove/WindowsApplication1.7z