我有5个PictureBoxes,我想在点击每个图像时更改图像。 例如,如果pictureBox1上显示的图像是" _1",当我点击它时,图像应该变为" _1x"反之亦然。我的if子句中的代码永远不会执行,我也不知道为什么。
这是我的代码:
private void Form1_Load(object sender, EventArgs e)
{
pb1.Image = Properties.Resources._1;
pb2.Image = Properties.Resources._2;
pb3.Image = Properties.Resources._3;
pb4.Image = Properties.Resources._4;
pb5.Image = Properties.Resources._10;
}
private void pb1_Click(object sender, EventArgs e)
{
if (pb1.Image == Properties.Resources._1)
{
pb1.Image = Properties.Resources._1x;
}
else { pb1.Image = Properties.Resources._1; }
}
答案 0 :(得分:0)
在将图像附加到Picturebox之前,您需要保留对图像的本地引用,否则它会始终创建新对象,因此比较失败。
试试这个:
public partial class Form1 : Form
{
Bitmap img1 = Properties.Resources._1;
Bitmap img2 =Properties.Resources._2;
Bitmap img3 = Properties.Resources._3;
Bitmap img4 = Properties.Resources._4;
Bitmap img10 = Properties.Resources._10;
Bitmap img1x = Properties.Resources._1x
public Form1()
{
InitializeComponent();
pb1.Image = img1; //assign image1 to picturebox here
pb2.Image = img2;
pb3.Image = img3;
pb4.Image = img4;
pb10.Image = img10;
}
private void pb1_Click(object sender, EventArgs e)
{
if (pb1.Image == img1)
{
pb1.Image = img1x ;
}
else { pb1.Image = img1; }
}
}