简体   繁体   中英

Toggle background image with button click

This is my first post so I apologise if I do anything wrong :-)

I know a little bit about coding but I'm new to C#. I've created a form and I want to toggle the form BackgroundImage between two different images when a "Change Background" button is clicked. I found this code that will toggle between image and no image:

this.BackgroundImage = this.BackgroundImage == null ? Properties.Resources.image1 : null;

I thought I might be able to use it to achieve what I want but I couldn't get it to work. I'm guessing I need completely different code? I thought an "if" statement would be the way to go but I can't figure that out either.

Thanks in advance for any help.

Imagine you want to switch between 2 images. Use a flag to determine which one is up and then change the image based on that flag.

private int imgId=0;

Then button_click should contains:

this.BackgroundImage = imgId==0 ? Properties.Resources.image2 : Properties.Resources.image1;

imgId=imgId==0 ?1:0;
this.BackgroundImage = this.BackgroundImage == null ? Properties.Resources.image1 : null;

checks if the background is null, then if it is null returns an image and otherwise returns null. You can use this code for your problem but I advise you to create a variable to check instead of the two images. The equality operator on full images isn't that performant ;)

I'll try to code really clear here and leave the difficult if operator out for better understanding.

//This variable doesn't erase if it's outside the function
private bool firstImage = true; 

public function SwitchImage(){
   if (firstImage == true){
       //set background
       this.BackgroundImage = Properties.Resources.image2
       //update var
       firstImage = false;
   } else {
       //set background
       this.BackgroundImage = Properties.Resources.image1
       //update var
       firstImage = true;
   }
}

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