C#切换按钮不起作用

时间:2017-06-23 14:11:35

标签: c# togglebutton

因此,我测试了许多其他类型的切换按钮制造商,但这些都不起作用。 但有人可以说出为什么这不起作用:

private void button11_Click(object sender, EventArgs e)
        {
            bool on = true;
            {
                if (!on)

                    button11.Text = "Off";
                    button11.BackColor = Color.LightGray;
                    on = true;
            }

            if (on == true)
            {
                button11.Text = "On";
                button11.BackColor = Color.DimGray;
                on = false;
            }
        }

感谢

2 个答案:

答案 0 :(得分:1)

您的解决方案无法正常运行,因为每次点击都会执行初始化ontrue的代码。 这意味着您的if语句始终检查相同的真值。

您应该通过跟踪方法中的on标志来实现它,然后在其中进行检查。如下所示:

public partial class Form1 : Form
{ 
    bool button1on = false;

    private void button1_Click(object sender, EventArgs e)
    {
        if(button1on)
        {
            button1on = false;
            button11.Text = "Off";
            button11.BackColor = Color.LightGray;
        }
        else
        {
            button1on = true;
            button11.Text = "On";
            button11.BackColor = Color.DimGray;
        }
    }
}

答案 1 :(得分:0)

我认为这就是你要找的东西。只需在您的函数之外声明connect(tableWidget->selectionModel(), &QItemSelectionModel::selectionChanged, [&](const QItemSelection&, const QItemSelection&) { QTimer::singleShot(0, [&]() { qDebug() << "selected =" << tableWidget->selectionModel()->selectedIndexes() << endl; }); }); 并修复on语句。

请注意,我将第二个if语句更改为if。如果您想使用else,则需要使用if。否则,第一个else if块会将if设置为on,然后第二个false会看到if并将on == false设置回on 1}}。

true
相关问题