【问题标题】:Toggling the appearance of a button winform切换按钮 winform 的外观
【发布时间】:2012-09-08 02:49:10
【问题描述】:

我在面板中有一个按钮列表(动态生成)。在我的应用程序中,当单击其中一个按钮时,它的外观应该会改变。如果用户更改选择并单击列表中的另一个按钮,则新按钮会更改外观,而旧按钮将返回其默认外观。
单击完全不相关的按钮可确认选择。

我该怎么做?改变外观并不是真正的问题,但知道有一个先前的选择并恢复是。

谢谢。

【问题讨论】:

  • 不加评论的否决投票对任何人都不是很有用。

标签: c# winforms button


【解决方案1】:

有一个存储当前按钮的变量,确保在分配新单击的按钮之前更改先前分配的按钮的颜色

 private Button currentBtn = null;

为按钮创建一个通用事件处理程序

 protected void b_Click(object sender, EventArgs e)
    {
        Button snder  = sender as Button;

        //for the first time just assign this button
        if (currentBtn == null)
        {
            currentBtn = snder;
        }
        else //for the second time and beyond
        {
            //change the previous button to previous colour. I assumed red
            currentBtn.BackColor = System.Drawing.Color.Red;

            //assign the newly clicked button as current
            currentBtn = snder;
        }

        //change the newly clicked button colour to "Active" e.g green
        currentBtn.BackColor = System.Drawing.Color.Green;
    }

【讨论】:

    【解决方案2】:

    为面板中的所有按钮创建一个按钮单击事件处理程序并在那里处理所有更新:

    private void MyToggleButton_Click(object sender, EventArgs e) {
        // Set all Buttons in the Panel to their 'default' appearance.
        var panelButtons = panel.Controls.OfType<Button>();
        foreach (Button button in panelButtons) {
            button.BackColor = Color.Green;
            // Other changes...
        }
    
        // Now set the appearance of the Button that was clicked.
        var clickedButton = (Button)sender;
        clickedButton.BackColor = Color.Red;
        // Other changes...
    }
    

    【讨论】:

      【解决方案3】:

      能不能不用变量来存储当前选中的按钮

      伪代码

      按钮 b = selectedButton

      在点击事件中

      如果 b != 发件人

      还原b

      b = 新选择的按钮

      【讨论】:

        猜你喜欢
        • 2019-10-29
        • 1970-01-01
        • 2018-03-19
        • 2013-08-22
        • 2021-08-29
        • 2014-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多