gpt4 book ai didi

c# - 如何从另一个类更改按钮的属性?

转载 作者:行者123 更新时间:2023-11-30 17:44:23 24 4
gpt4 key购买 nike

我有四个按钮,每个按钮可以有三种可能的颜色(背景色):黄色、绿色、蓝色。

我在另一个类中有一个方法,我想从中更改这些按钮的颜色。此方法将在按钮上的 MouseUp 事件上调用,专为右键单击而设计。

这些是按钮的 Action 监听器:

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;
}
}

但是,当我使用此方法时,应用程序中没有任何反应。没有出现任何类型的错误。如果我使用消息框来查看 switch case 是否可以处理参数,代码可以工作,但颜色更改不起作用。

最佳答案

您也可以使用“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);
}
}

关于c# - 如何从另一个类更改按钮的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29690469/

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