Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple ON/OFF toggle button with image

I'm working on a WinForms project where I'm trying to create an ON/OFF toggle button that uses two separate images (both located in project resources) for both the "ON" setting, and the "OFF" setting.

Based on what I've found online, I've used a CheckBox with its appearance set to "Button".

Here is the code I've got so far for my button:

    private void ToggleButton_CheckedChanged(object sender, EventArgs e)
    {
        if (ToggleButton.Checked)
        {
            ToggleButton.BackgroundImage.Equals(Properties.Resources.ToggleButton_ON);
        }
        else
        {
            ToggleButton.BackgroundImage.Equals(Properties.Resources.ToggleButton_OFF);
        }
    }

For some reason nothing happens when I click on the button, and I'm not sure what I've done wrong here.

Basically, I'd like the background image to cycle back and fourth between ToggleButton_ON and ToggleButton_OFF when the user clicks on the button.

like image 882
Patrick Avatar asked Oct 19 '22 16:10

Patrick


1 Answers

Change your code to:

   private void ToggleButton_CheckedChanged(object sender, EventArgs e)
    {
        if (ToggleButton.Checked)
            ToggleButton.BackgroundImage = Properties.Resources.ToggleButton_ON;
        else
            ToggleButton.BackgroundImage = Properties.Resources.ToggleButton_OFF;
    }

The .Equals is for checking equality which you can override in your own classes.

like image 184
Vahid K. Avatar answered Oct 27 '22 23:10

Vahid K.