如何创建一个函数来重新定位和调整一组控件的大小
How can I make a function to relocate and resize a set of controls
我有 10 个面板都可见 = false 并且有 10 个按钮
- 面板名称 = p1、p2、p3...等等
- 按钮名称 = b1、b2、b3...等等
我想要点击按钮(b1)
- 使面板 (p1) 可见 = true
- 重新定位和调整面板大小
所有面板的新位置和新尺寸都相同,
我可以让一个函数进行重新定位和调整大小,而不是像这样多次编写代码吗
private void b1_Click(object sender, EventArgs e)
{
p1.Visible = true;
p1.Location = new System.Drawing.Point(9, 247);
p1.Size = new System.Drawing.Size(1120, 464);
}
您可以将所有按钮的点击事件分配给同一个事件处理程序。参数 sender 是触发事件的对象,在您的情况下它是您的按钮之一。然后检查发件人的文本或名称 属性 并找出单击了哪个按钮。对于面板,您可以创建一个带有面板类型参数的方法并执行您想要的操作。
private void btn_Click(object sender, EventArgs e)
{
// here put code to hide all panels
//...
//then show and relocate the panel related the clicked button as follows
switch ((sender as Button).Name) //or button's Text
{
case "b1":
showPanel(pl);
break;
case"b2":
showPanel(p2);
break;
//other cases
//...
}
}
private void showPanel(Panel pnl)
{
//show and relocate
pnl.Visible = true; //I consider pnl.Show(); as it's more readable
//...
}
不要忘记在点击事件开始时隐藏所有面板。如果您的控件中除了这 10 个之外没有任何其他面板,您可以使用以下方法。
private void hidePanels()
{
foreach (Control c in yourControl.Controls) //replace yourControl with the control that is the container of your panels e.g. your form
{
if (c is Panel) c.Visible = false; //or c.Hide();
}
}
我还没有测试过这段代码,但它应该可以工作。
我有 10 个面板都可见 = false 并且有 10 个按钮
- 面板名称 = p1、p2、p3...等等
- 按钮名称 = b1、b2、b3...等等
我想要点击按钮(b1)
- 使面板 (p1) 可见 = true
- 重新定位和调整面板大小
所有面板的新位置和新尺寸都相同, 我可以让一个函数进行重新定位和调整大小,而不是像这样多次编写代码吗
private void b1_Click(object sender, EventArgs e)
{
p1.Visible = true;
p1.Location = new System.Drawing.Point(9, 247);
p1.Size = new System.Drawing.Size(1120, 464);
}
您可以将所有按钮的点击事件分配给同一个事件处理程序。参数 sender 是触发事件的对象,在您的情况下它是您的按钮之一。然后检查发件人的文本或名称 属性 并找出单击了哪个按钮。对于面板,您可以创建一个带有面板类型参数的方法并执行您想要的操作。
private void btn_Click(object sender, EventArgs e)
{
// here put code to hide all panels
//...
//then show and relocate the panel related the clicked button as follows
switch ((sender as Button).Name) //or button's Text
{
case "b1":
showPanel(pl);
break;
case"b2":
showPanel(p2);
break;
//other cases
//...
}
}
private void showPanel(Panel pnl)
{
//show and relocate
pnl.Visible = true; //I consider pnl.Show(); as it's more readable
//...
}
不要忘记在点击事件开始时隐藏所有面板。如果您的控件中除了这 10 个之外没有任何其他面板,您可以使用以下方法。
private void hidePanels()
{
foreach (Control c in yourControl.Controls) //replace yourControl with the control that is the container of your panels e.g. your form
{
if (c is Panel) c.Visible = false; //or c.Hide();
}
}
我还没有测试过这段代码,但它应该可以工作。