我是C#的新手,我正在使用Windows窗体。
我Form1
有20 buttons
和20 user controls
。我想做的是:
当我点击button1
user control1
显示,其余user controls
隐藏时,请点击button2
user control2
显示,其余{{1}隐藏,点击user controls
button3
显示,其他user control3
隐藏,依此类推。我可以使用user controls
显示一个UserControl.visible = True
,并通过设置user control
的其余部分隐藏其余内容,但我不想编写太多代码。
因此,我使用以下简单代码在单击相关user controls visibility = False
时仅显示一个user control
并隐藏其余button
,但此代码无法正常运行没有错误,但user controls
仍然可见。
任何人都知道为什么这段代码没有显示user controls
并隐藏其余部分?我也很乐意听到其他想法。谢谢
one user control
答案 0 :(得分:5)
您的代码未按预期运行的原因是这种情况:
if (ctrl.GetType() == typeof(UserControl))
GetType()
会返回永远不会是UserControl
的实际类型,但会从中获取一些类型。
请改用以下内容
if (ctrl is UserControl)
答案 1 :(得分:3)
Button
有一个属性Tag
。将所有按钮的UserControl
引用保存在tag属性中:
button1.Tag = UserControl1;
button2.Tag = UserControl2;
button3.Tag = UserControl3;
//and so on...
//you can do it FormLoad event handler
现在将所有按钮订阅到单个Click
事件:
button1.Click += button1_Click; //I am using "button1_Click" for all buttons
button2.Click += button1_Click;
button3.Click += button1_Click;
现在主要的是:
private void button1_Click(object sender, EventArgs e)
{
Button btn = sender as Button; //cast the sender
//hide all user controls
foreach (Control ctrl in this.Controls)
{
if (ctrl .GetType() == typeof(UserControl))
{
ctrl .Visible = false;
}
}
//show the usercontrol saved in "Tag" of the current button
(btn.Tag as UserControl).Visible = True;
}
注意:如果您收到任何错误,我还没有编译此代码。请告诉我。
答案 2 :(得分:2)
此代码对我有用:
var pairs = new[]
{
new { Button = button1, UserControl = userControl1 },
new { Button = button2, UserControl = userControl2 },
new { Button = button3, UserControl = userControl3 },
new { Button = button4, UserControl = userControl4 },
new { Button = button5, UserControl = userControl5 },
new { Button = button6, UserControl = userControl6 },
new { Button = button7, UserControl = userControl7 },
new { Button = button8, UserControl = userControl8 },
new { Button = button9, UserControl = userControl9 },
new { Button = button10, UserControl = userControl10 },
new { Button = button11, UserControl = userControl11 },
new { Button = button12, UserControl = userControl12 },
new { Button = button13, UserControl = userControl13 },
new { Button = button14, UserControl = userControl14 },
new { Button = button15, UserControl = userControl15 },
new { Button = button16, UserControl = userControl16 },
new { Button = button17, UserControl = userControl17 },
new { Button = button18, UserControl = userControl18 },
new { Button = button19, UserControl = userControl19 },
new { Button = button20, UserControl = userControl20 },
};
foreach (var pair in pairs)
{
pair.UserControl.Visible = false;
pair.Button.Click += (s, e2) =>
{
foreach (var pair2 in pairs) { pair2.UserControl.Visible = false; }
pair.UserControl.Visible = true;
};
}
我故意创建一个按钮/用户控件对列表,以便它们是硬编码的,我不必按名称查找它们。这种重构和验证代码的方式更好。
然后第一个foreach
循环只是将click事件连接起来,这使得除了配对的用户控件之外,所有用户控件都不可见。
只需在Form_Load
事件处理程序中弹出此代码即可。