If picturebox.image == Properties.Resources.ImageA

2020-03-26 07:18发布

Im making few buttons(picturebox) that then you click them they change image.

I tryed this code but it always skips to else.

Images are loaded from resources.

private void pictureBox7_Click(object sender, EventArgs e)
    {
       if (pictureBox7.Image == KaminuSkaiciuokle.Properties.Resources.IcopalA)
       {
           pictureBox7.Image = KaminuSkaiciuokle.Properties.Resources.IcopalB;
       }
       else
       {
            pictureBox7.Image = KaminuSkaiciuokle.Properties.Resources.IcopalA;
       }
    }

Figured that out.

Insted comparing picturebox.image I set picturebox.tag and compare.

pictureBox7.Tag = "B";
if (pictureBox7.Tag.ToString() == "A")
   {
        pictureBox7.Image = KaminuSkaiciuokle.Properties.Resources.IcopalB;
        pictureBox7.Tag = "B";
   }
   else
   {
        pictureBox7.Image = KaminuSkaiciuokle.Properties.Resources.IcopalA;
        pictureBox7.Tag = "A";
   }

2条回答
欢心
2楼-- · 2020-03-26 08:03

You should keep local reference to your resources, because when you invoke KaminuSkaiciuokle.Properties.Resources... you will always get new instance of object:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    Bitmap _icopalABitmap = KaminuSkaiciuokle.Properties.Resources.IcopalA;
    Bitmap _icopalBBitmap = KaminuSkaiciuokle.Properties.Resources.IcopalB;

    private void pictureBox1_Click(object sender, EventArgs e)
    {            
        if (pictureBox7.Image == _icopalABitmap)
        {
            pictureBox7.Image = _icopalBBitmap;
        }
        else
        {
            pictureBox7.Image = _icopalABitmap;
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        pictureBox7.Image = _icopalABitmap;
    }
}
查看更多
家丑人穷心不美
3楼-- · 2020-03-26 08:08

please attention this code:

Bitmap _icopalABitmap = KaminuSkaiciuokle.Properties.Resources.IcopalA;

_icopalABitmap:it is name you ideal that. KaminuSkaiciuokle: it aqual your project name. IcopalA: is your picture name

查看更多
登录 后发表回答