C# Visual Studio 2012动态PictureBox图像

C# Visual Studio 2012动态PictureBox图像,c#,visual-studio,visual-studio-2012,picturebox,C#,Visual Studio,Visual Studio 2012,Picturebox,我有一个简短的问题,我一直在努力解决一些理论上应该很简单的问题 我想在Visual Studio 2012中从图片框中创建一个动态按钮,每次单击该按钮时都会更改图像 if (pictureBox4.BackgroundImage == MyProject.Properties.Resources._1) pictureBox4.BackgroundImage = MyProject.Properties.Resources._2; else if (pictureBox4.Backgro

我有一个简短的问题,我一直在努力解决一些理论上应该很简单的问题

我想在Visual Studio 2012中从图片框中创建一个动态按钮,每次单击该按钮时都会更改图像

if (pictureBox4.BackgroundImage == MyProject.Properties.Resources._1)
    pictureBox4.BackgroundImage = MyProject.Properties.Resources._2;
else if (pictureBox4.BackgroundImage == MyProject.Properties.Resources._2)
    pictureBox4.BackgroundImage = MyProject.Properties.Resources._1;
现在,这并不是很好。它不会检测当前显示的图像并输入
if
语句。所以,我用这种方法测试了它

int b = 1; 

if (b == 1)
{
    pictureBox4.BackgroundImage = MyProject.Properties.Resources._2;
    b = 2;
}

if (b == 2)
{
    pictureBox4.BackgroundImage = MyProject.Properties.Resources._1;
    b = 1;
}
接近。。。但是没有雪茄。当我点击它的形象确实改变,但只有一次;如果我再次单击它,它将保持不变


所以。。。现在怎么办?谢谢您的回答。

您在两个if子句(参考资料)中使用了相同的图像

此外,正如TaW指出的,当b==1时,设置b=2并检查b==2。两个if子句都是真的。第二个if应该是“else if”

当然,您可以使用else子句:

    if (b == 1)
    {
        pictureBox4.BackgroundImage = MyProject.Properties.Resources._2;
        b = 2;
    }
    else
    {   
        pictureBox4.BackgroundImage = MyProject.Properties.Resources._1;
        b = 1;
    }
或者,如果不需要整数变量,则可以尝试以下方法:

1) 只需从资源中提取一次图像,然后将其放入静态成员中

    private static readonly Image Image1 = MyProject.Properties.Resources._1;
    private static readonly Image Image2 = MyProject.Properties.Resources._2;
2) 更改条件以使用静态副本而不是资源属性(每次都返回一个新对象)


这是我的任务解决方案:在
MyProject
中,我有一个名为
Resource1
的资源文件和六个
图像
,从
\u0
\u5

int index = 0;
private void anImageButton_Click(object sender, EventArgs e)
{
    index = (index + 1) % 6;
    anImageButton.Image = 
          (Bitmap)MyProject.Resource1.ResourceManager.GetObject("_" + index);
}

我使用了一个简单的
按钮anImageButton
,而不是
PictureBox
,但是它也可以用于
PictureBox

是事件处理程序方法中的第一行(int b=1;)还是类的全局?全局,在类中,对不起,我忘记指定了,如果我把它放在事件处理程序中,那就太傻了。。。他在每个if或else前面加了一个else子句,否则它将不起作用;-)(因为第一个更改将使第二个if为true,并且它将恢复该更改等等)您真的在两个if子句中都使用这一行吗?pictureBox4.BackgroundImage=MyProject.Properties.Resources.\u 2;可能是一种类型。更重要的是,他遗漏了else条款!是的,对不起,我是说资源。。。现在,奇怪的是,我再次运行了代码,但它根本不起作用,甚至连第一次点击都没有……呵呵。再次阅读我们的评论;-)你用else替换了第二个if?(见我编辑的答案和TaW的评论。)如果你错过了,它就不会更新了。好吧,我太傻了,没有把else放在那里。。。这解决了问题!所以它起作用了。。。buuuuut,我将把其中的许多列成一行,我不能为每个列创建20个整数,你知道为什么第一个方法不起作用吗??
    if (pictureBox4.BackgroundImage == Image2)
    {
        pictureBox4.BackgroundImage = Image1;
    }
    else
    {
        pictureBox4.BackgroundImage = Image2;
    }
int index = 0;
private void anImageButton_Click(object sender, EventArgs e)
{
    index = (index + 1) % 6;
    anImageButton.Image = 
          (Bitmap)MyProject.Resource1.ResourceManager.GetObject("_" + index);
}