我有四个按钮,每个按钮可以有三种颜色(backgorund):黄色,绿色,蓝色。
我在另一个类中有一个方法,我想从中改变这些按钮的颜色。此方法将在按钮上的MouseUp事件上调用,专为右键单击而设计。
这些是按钮的动作侦听器:
private void RightSeat_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
TableModel.ColorChange(2);
}
}
private void BottomSeat_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
TableModel.ColorChange(3);
}
}
private void LeftSeat_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
TableModel.ColorChange(4);
}
}
private void TopSeat_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
TableModel.ColorChange(1);
}
}
这是创建按钮的位置(设计师代码):
public void InitializeComponent()
{
this.LeftSeat = new System.Windows.Forms.Button();
this.RightSeat = new System.Windows.Forms.Button();
this.BottomSeat = new System.Windows.Forms.Button();
this.TopSeat = new System.Windows.Forms.Button();
//other generated code
}
public System.Windows.Forms.Button LeftSeat;
public System.Windows.Forms.Button RightSeat;
public System.Windows.Forms.Button BottomSeat;
public System.Windows.Forms.Button TopSeat;
这是第二堂课的代码。
public static void ColorChange(int btn)
{
TableView tw = new TableView();
switch (btn)
{
case 1:
tw.TopSeat.BackColor = Color.Yellow;
break;
case 2:
tw.RightSeat.BackColor = Color.Yellow;
break;
case 3:
tw.BottomSeat.BackColor = Color.Yellow;
break;
case 4:
tw.LeftSeat.BackColor = Color.Yellow;
break;
default:
break;
}
}
但是,当我使用此方法时,应用程序中没有任何反应。不会出现任何类型的错误。如果我使用消息框来查看切换案例是否可以处理参数,但颜色更改不起作用,则代码可以正常工作。
答案 0 :(得分:1)
您也可以使用“ref”
将按钮传递给方法public static void ColorChange(int btn, ref System.Windows.Forms.Button buttonToChange)
{
switch (btn)
{
case 1:
buttonToChange.BackColor = Color.Yellow;
break;
case 2:
buttonToChange.BackColor = Color.Yellow;
break;
case 3:
buttonToChange.BackColor = Color.Yellow;
break;
case 4:
buttonToChange.BackColor = Color.Yellow;
break;
default:
break;
}
}
然后您可以使用以下方法调用此方法:
private void TopSeat_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
TableModel.ColorChange(1, ref TopSeat);
}
}
答案 1 :(得分:0)
您需要找到现有表格" TableView"
Button btn = Application.OpenForms["TableView "].Controls["LeftSeat"] as Button;
btn.BackColor = Color.Yellow