我使用对象列表作为我的应用程序的输入,并且列表中的对象数量发生了变化。对于列表中的每个对象,我动态创建一个Panel并将它们添加到其他面板的控件
private void addPanel(string name, int positionFromLeft, Panel mainPanel)
{
Panel panel = new System.Windows.Forms.Panel();
panel.Name = name;
panel.Location = new System.Drawing.Point(50 + positionFromLeft, 160);
panel.BackColor = System.Drawing.Color.SteelBlue;
panel.Size = new System.Drawing.Size(120, 40);
panel.Click += new EventHandler(this.pClick);
mainPanel.Controls.Add(panel);
}
对于每个面板,我添加了一个更改面板颜色的单击事件处理程序:
private void pClick(object sender, EventArgs e)
{
Panel panel= (sender as Panel);
panel.BackColor = Color.Green;
}
如果每次面板第二次点击时,如何将颜色更改为其他颜色(红色等)?再次点击时将其更改回绿色等。基本上,每次点击都可以将面板颜色从绿色变为红色,反之亦然。它必须适用于每个面板,以便我可以将例如10个面板的颜色更改为绿色,将10个面板更改为红色,反之亦然。
答案 0 :(得分:0)
如果我做对了,你想要切换点击的面板。
private void pClick(object sender, EventArgs e)
{
Panel panel = (sender as Panel);
if (panel.BackColor == Color.Green) {
panel.BackColor = Color.Red;
} else if (panel.BackColor == Color.Red) {
panel.BackColor = Color.Green;
}
}
答案 1 :(得分:-1)
我找到了一个解决方案,非常感谢。
private void pClick(object sender, EventArgs e)
{
Panel panel = (sender as Panel);
if (panel.BackColor == Color.SteelBlue)
{
panel.BackColor = Color.Green;
}
else if (panel.BackColor == Color.Green)
{
panel.BackColor = Color.Red;
}
else if (panel.BackColor == Color.Red)
{
panel.BackColor = Color.Green;
}
}