简体   繁体   中英

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

in the on click event

if b != sender

revert b

b = new selected button

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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