gpt4 book ai didi

c# - 如何制作具有相同行为的不同面板?

转载 作者:太空宇宙 更新时间:2023-11-03 22:31:36 25 4
gpt4 key购买 nike

你好,我正在制作带面板的 10x10 立方体,当你点击面板 X 次时面板需要改变颜色,但代码太大了,有没有其他方法可以让代码不那么长?

这是我的代码:

int cont1 = 0, cont2 = 0, cont3 = 0, cont4 = 0, cont5 = 0, cont6 = 0, cont7 = 0, cont8 = 0, cont9 = 0, cont10 = 0;

然后是更改颜色的事件(我所有的面板都有相同的代码,但区别在于“cont”和面板名称):

 private void panel1_MouseClick(object sender, MouseEventArgs e)
{
cont1++;
if (cont1 <= 5)
{
panel1.BackColor = Color.SlateBlue;
}
if (cont1 >=5)
{
panel1.BackColor = Color.Cyan;
}
if (cont1 >= 10)
{
panel1.BackColor = Color.Lime;
}
if (cont1 >= 15)
{
panel1.BackColor = Color.Yellow;
}
if (cont1 >= 20)
{
panel1.BackColor = Color.Red;
}
}

//other panel
private void panel2_MouseClick(object sender, MouseEventArgs e)
{
cont2++;
if (cont2 <= 5)
{
panel2.BackColor = Color.SlateBlue;
}
if (cont2 >= 5)
{
panel2.BackColor = Color.Cyan;
}
if (cont2 >= 10)
{
panel2.BackColor = Color.Lime;
}
if (cont2 >= 15)
{
panel2.BackColor = Color.Yellow;
}
if (cont2 >= 20)
{
panel2.BackColor = Color.Red;
}
}

注意:每个面板都会改变颜色,不是同时发生的实际上使用 4x4,但 10x10 对我来说很大

最佳答案

您实际上不需要创建大量变量,因为您需要跟踪控制状态。您可以利用 control Tags 的存在并减少您编写的代码量。

Be it 1000 x 1000 panels the below method would work flawlessly for your usecase. All you need do is point all target panel mouseClick to it and allow it handle the rest.

private void panel_MouseClick(object sender, MouseEventArgs e)
{
Control ctrl = sender as Control;

//get previous value from control tag or start at 0
int count = ctrl.Tag == null ? 0 : (int)ctrl.Tag;

//set backcolor of control based on tag number
if (count >= 20) ctrl.BackColor = Color.Red;
else if (count >= 15) ctrl.BackColor = Color.Yellow;
else if (count >= 10) ctrl.BackColor = Color.Lime;
else if (count >= 5) ctrl.BackColor = Color.Cyan;
else ctrl.BackColor = Color.SlateBlue;

// if (count == xx)
//{// you may want to reset count after a certain number. Do that here...}

ctrl.Tag = ++count;
}

关于c# - 如何制作具有相同行为的不同面板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57367360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com