按钮.BackgroundImage =;什么也不做
我想在单击一次时更改按钮的背景图像,然后在再次单击时将其更改回原始图像(并且它将反复工作)。我的代码片段是这样的:
private void handButton_Click(object sender, EventArgs e)
{
if (handButton.BackgroundImage == WindowsFormsApplication1.Properties.Resources.Hands_Right)
{
handButton.BackgroundImage = WindowsFormsApplication1.Properties.Resources.Hands_Left;
}
else if (handButton.BackgroundImage == WindowsFormsApplication1.Properties.Resources.Hands_Left)
{
handButton.BackgroundImage = WindowsFormsApplication1.Properties.Resources.Hands_Right;
}
}
但是当我运行程序并单击按钮时;什么也没发生。图像大小为32x32,我可以清楚地看到原始图像。单击时,原始图像保留在那里。没有其他变量影响此代码段(至少,搜索“handButton”只能从此代码段获取结果)。
有什么建议吗?我没有任何错误,所以我怀疑我做错了。有没有更好的方法来来回更改图像?
I want to change the BackgroundImage of a button when you click once, and then change it back to the original when clicked again (and it will work over and over). My code snippet is this:
private void handButton_Click(object sender, EventArgs e)
{
if (handButton.BackgroundImage == WindowsFormsApplication1.Properties.Resources.Hands_Right)
{
handButton.BackgroundImage = WindowsFormsApplication1.Properties.Resources.Hands_Left;
}
else if (handButton.BackgroundImage == WindowsFormsApplication1.Properties.Resources.Hands_Left)
{
handButton.BackgroundImage = WindowsFormsApplication1.Properties.Resources.Hands_Right;
}
}
But when I run the program and click the button; nothing happens. The images are 32x32, and I can see the original image clearly. When clicked, the original image stays there. There are no other variables affecting this snippet (at least, a search for "handButton" only gets results from this snippet).
Any suggestions? I have no errors, so I suspect that I'm going about this wrong. Is there a better way to change images back and forth?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Properties.Resources 类并不按您想象的方式工作。像 Hands_Right 这样的属性实际上返回一个新的位图,而不是之前返回的任何对象。这不会很好地工作,因为修改位图也会修改其设计中的属性。
所以你的 if() 语句表达式永远不会计算为 true。单独跟踪按钮状态。
The Properties.Resources class doesn't work the way you think. A property like Hands_Right actually returns a new bitmap, not whatever object was returned previously. That wouldn't work very well since modifying the bitmap would also modify the property from its design.
So your if() statement expressions never evaluate to true. Keep track of the button state separately.