【问题标题】:on off button stays at Onon off 按钮保持在 On
【发布时间】:2016-09-23 06:01:44
【问题描述】:

我想创建一个切换按钮,但它停留在开启状态。如何将按钮从打开切换到关闭。

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

【问题讨论】:

    标签: c# button


    【解决方案1】:

    您总是将文本设置为On。更改您的 else 块:

    else if (button.Text == "On")
    {
        button.Text = "Off"; // here !!!
        button.BackColor = Color.Red;
    }
    

    或者使用这个解决方案来创建一个 ToggleButton: ToggleButton in C# WinForms

    【讨论】:

    • 我已将其更改为 ""off"" 仍停留在 On.
    【解决方案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"

    【讨论】:

      【解决方案3】:

      应该是这样的:creation + 正在改变点击状态:

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

      【讨论】:

        猜你喜欢
        • 2015-04-20
        • 2018-11-16
        • 2018-08-02
        • 1970-01-01
        • 2017-02-12
        • 1970-01-01
        • 2014-09-23
        • 2022-07-17
        • 1970-01-01
        相关资源
        最近更新 更多