Simple on / off switch button with image

I am working on a WinForms project where I am trying to create an ON / OFF toggle button that uses two separate images (both are in the project resources) for both the β€œON” parameter and the β€œOFF” parameter.

Based on what I found on the Internet, I used CheckBox with its appearance set to "Button".

Here is the code that I still have 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 a button, and I'm not sure what I did wrong here.

Basically, I need the background image to switch back and the fourth between ToggleButton_ON and ToggleButton_OFF when the user clicks the button.

+5
source share
1 answer

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

.Equals to check for equality, which you can override in your own classes.

+3
source

Source: https://habr.com/ru/post/1242452/


All Articles