C# 单击更改PictureBox图像

C# 单击更改PictureBox图像,c#,winforms,picturebox,C#,Winforms,Picturebox,我有5个PictureBox,我想在单击每个图片框时更改图像。 例如,如果pictureBox1上显示的图像为“_1”,当我单击它时,图像应更改为“_1x”,反之亦然。if子句中的代码从未执行过,我也不知道为什么 这是我的密码: private void Form1_Load(object sender, EventArgs e) { pb1.Image = Properties.Resources._1; pb2.Image = Properti

我有5个PictureBox,我想在单击每个图片框时更改图像。 例如,如果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; }
    }

在将图像附加到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; }
    }
  }

您需要找到一种方法来跟踪指定的图像,也许可以使用.Tag属性
pb1.Image==Properties.Resources.\u 1
不进行图像比较;这将测试它们是否是相同的对象。谢谢。我试过你的代码,效果很好。如果你能帮我的话,我还有一个问题。我的onClick的完整代码是:请阅读:如果上面的代码有效,那么接受它作为答案,并发布另一个新问题。。。