我想创建一个切换按钮,但它仍处于打开状态。如何将按钮从开启切换到关闭。
private void Form2_Load(object sender, EventArgs e){
Button button = new Button();
button.Location = new Point(200, 30);
button.Text = "Off";
this.Controls.Add(button);
if (button.Text != "On")
{
button.Text = "On";
button.BackColor = Color.Green;
}
else if (button.Text == "On")
{
button.Text = "On";
button.BackColor = Color.Red;
}
}
答案 0 :(得分:2)
您需要输入代码以更改按钮在该按钮的Click
事件处理程序中的外观:
private void Form2_Load(object sender, EventArgs e){
Button button = new Button();
button.Location = new Point(200, 30);
button.Text = "Off";
this.Controls.Add(button);
// subscribe to the Click event
button.Click += button_Click;
}
// the Click handler
private void button_Click(object sender, EventArgs e)
{
Button button = sender as Button;
if (button == null) return;
if (button.Text != "On")
{
button.Text = "On";
button.BackColor = Color.Green;
}
else if (button.Text == "On")
{
button.Text = "Off";
button.BackColor = Color.Red;
}
}
请注意,在else
块中,您设置了错误的文字。将其更改为"Off"
。
答案 1 :(得分:1)
您始终将文字设置为On
。更改你的其他块:
else if (button.Text == "On")
{
button.Text = "Off"; // here !!!
button.BackColor = Color.Red;
}
或者使用此解决方案创建ToggleButton: ToggleButton in C# WinForms
答案 2 :(得分:0)
应该是这样的:点击时创建 + 更改状态:
private void Form2_Load(object sender, EventArgs e){
// Initial creation
Button button = new Button() {
Location = new Point(200, 30),
Text = "Off",
BackColor = Color.Red,
Parent = this,
};
// Click handle, let it be lambda
// Toggle on click (when clicked change On -> Off -> On ...)
button.Click += (s, ev) => {
Button b = sender as Button;
if (b.Text == "On") {
// when "On" change to "Off"
b.Text = "Off";
b.BackColor = Color.Red;
}
else {
b.Text = "On";
b.BackColor = Color.Green;
}
};
}