简体   繁体   English

切换按钮winform的外观

[英]Toggling the appearance of a button winform

I have a list of buttons in a panel (generated dynamically). 我在面板中有一个按钮列表(动态生成)。 In my application, when one of the buttons is clicked, its appearance should change. 在我的应用程序中,当单击其中一个按钮时,其外观应发生变化。 If the user changes their choice and clicks another button in the list, the new button changes appearance while the old one returns to its default appearance. 如果用户更改选择并单击列表中的另一个按钮,则新按钮将更改外观,而旧按钮将恢复其默认外观。
A click on a completely unrelated button serves to confirm the choice. 单击完全不相关的按钮可确认选择。

How do I go about this? 我该怎么办? Changing the appearance is not really the problem but knowing there is a previous selection and reverting is. 更改外观并不是真正的问题,但知道存在先前的选择并还原就可以了。

Thanks. 谢谢。

Create a Button click event handler for all the Buttons in your Panel and handle all updates there: 为面板中的所有按钮创建一个按钮单击事件处理程序,并在那里处理所有更新:

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

Can you not use a variable to store the current selected button 您可以不使用变量来存储当前选择的按钮吗

Pseudo code 伪代码

Button b = selectedButton 按钮b = selectedButton

in the on click event 在点击事件中

if b != sender 如果b!=发送者

revert b 恢复b

b = new selected button b =新选择的按钮

Have a variable that stores the current button, making sure you change the colour of the previously assigned button before assigning a newly clicked button 有一个存储当前按钮的变量,请确保在分配新单击的按钮之前先更改先前分配的按钮的颜色

 private Button currentBtn = null;

Create a common event handler for the buttons 为按钮创建一个公共事件处理程序

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM