使用 Image 更改选中状态 [英] Change checked state with Image

查看:33
本文介绍了使用 Image 更改选中状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码,绑定到 PictureBoxClick 事件,以在单击 PictureBox 时更改图像.

I use this code, bound to PictureBox's Click event, to change the image when the PictureBox is clicked.

private void pictureBox1_Click(object sender, EventArgs e) //domanda else if
        {
            if (checkBox1.Checked == false)
            {
                pictureBox1.Image = Properties.Resources.On;
                checkBox1.Checked = true;
            }
            else
            {
                pictureBox1.Image = Properties.Resources.Off;
                checkBox1.Checked = false;
            }
        }

它有效,但如果我在 PictureBox 中有开启"图像,点击它不会改变图像,它仍然是开启"图像.我试过这段代码,但它对我不起作用:

It works, but if I have the "on" image in the PictureBox, clicking it does not change the image, it is still the "on" image. I tried this code but it does not work for me:

 private void Form1_Load(object sender, EventArgs e)
        {          
    if (pictureBox1.Image == Properties.Resources.On)
                    {                        
                        checkBox1.Checked = true;
                    }
                    else
                    {                            
                        checkBox1.Checked = false;
                    }
}

我需要图像 = 复选框 选中关闭图像 = 未选中复选框

I need image on = checkedbox Checked image off = checkedbox not Checked

推荐答案

当您执行 pictureBox1.Image == Properties.Resources.On 时,您正在检查它们是否等于相同的引用.答案是它们不是,因此即使图像相同,实际参考也不同.相反,您可以使用 PictureBox 的 Tag属性来存储当前图像数据.例如

When you do pictureBox1.Image == Properties.Resources.On you're checking if they're equal to the same reference. The answer is that they're not, so even though the images are the same, the actual references are not. Instead you can use the PictureBox's Tag property to store the current image data. For example

 if (checkBox1.Checked == false)
 {
     pictureBox1.Image = Properties.Resources.On;
     pictureBox1.Tag = "ON";
     checkBox1.Checked = true;            
 }
 else
 {
     pictureBox1.Image = Properties.Resources.Off;
     pictureBox1.Tag = "OFF";
     checkBox1.Checked = false;
 }

当你想查看它有什么图像时,你可以阅读该标签

You can then read that Tag when you want to see what image it has

if (pictureBox1.Tag.ToString() == "ON")
    checkBox1.Checked = true;
else                            
    checkBox1.Checked = false;

作为旁注,Tag 属性包含 object 类型,因此您不必存储和比较字符串,例如您可以添加枚举.(尽管在这种情况下,一个字符串就足够了).

As a side note, the Tag property holds object types so you don't have to store and compare strings, you can add enums for example. (Although in this case a string should suffice).

这篇关于使用 Image 更改选中状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆