我正在处理一个有很多按钮的表单。当用户单击一个按钮时,背景应该改变颜色。如果他们点击表单上的另一个按钮,它的背景应该改变颜色,而之前的按钮颜色应该恢复到原来的颜色。
我可以通过在每个按钮中进行硬编码来做到这一点,但这种形式有很多按钮。我相信必须有一种更有效的方法来做到这一点
到目前为止我有这个
foreach (Control c in this.Controls)
{
if (c is Button)
{
if (c.Text.Equals("Button 2"))
{
Btn2.BackColor = Color.GreenYellow;
}
else
{
}
}
}
我可以让 Btn2 的背景发生变化。我将如何更改表单中所有其他按钮的背景。我有什么想法可以做到这一点而不必对每个按钮进行硬编码。
最佳答案
无论表单上的按钮数量如何,下面的代码都可以正常工作。只需将 button_Click
方法设置为所有按钮的事件处理程序。当你点击一个按钮时,它的背景会改变颜色。当您点击任何其他按钮时,该按钮的背景会改变颜色,而之前彩色按钮的背景将恢复为默认背景颜色。
// Stores the previously-colored button, if any
private Button lastButton = null;
...
// The event handler for all button's who should have color-changing functionality
private void button_Click(object sender, EventArgs e)
{
// Change the background color of the button that was clicked
Button current = (Button)sender;
current.BackColor = Color.GreenYellow;
// Revert the background color of the previously-colored button, if any
if (lastButton != null)
lastButton.BackColor = SystemColors.Control;
// Update the previously-colored button
lastButton = current;
}
关于c# - 更改除单击按钮之外的所有按钮背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14459688/