[英]Toggle the picture of picture box with picture box on_click c#
我的图片框中有一张图片,使用的资源是我想在单击图片框内的icon.png时将其更改为图片,然后在再次单击图片框时将其更改为icon1.png icon.png
private void pictureBox10_Click(object sender, EventArgs e)
{
if (pictureBox10.ImageLocation != @"icon1.png")
{
var image = Image.FromFile(@"icon1.png");
pictureBox10.Image = image;
}
if (pictureBox10.ImageLocation == @"icon1.png")
{
var image = Image.FromFile(@"icon.png");
pictureBox10.Image = image;
}
}
但它不起作用,请帮我解决这个问题。
将图像分配给Image属性时,未从图像位置获取null,因为它没有设置。 有几种方法可以解决此问题:
更改分配,以便您使用ImageLocation分配
pictureBox10.ImageLocation = @"icon1.png";
更改检查以查看Image属性是否等于您的新Image
pictureBox10.Image == Image.FromFile(@"icon.png");
设置图像属性的同时设置图像位置
pictureBox10.Image == Image.FromFile(@"icon.png"); pictureBox10.ImageLocation = @"icon.png" ;
我觉得第二个可能不相等,您可能想尝试第一个或第三个
建议的代码:
private void pictureBox10_Click(object sender, EventArgs e)
{
if (pictureBox10.ImageLocation != @"icon1.png")
{
pictureBox10.ImageLocation = @"icon1.png"
}
if (pictureBox10.ImageLocation == @"icon1.png")
{
pictureBox10.ImageLocation = @"icon.png";
}
}
要么:
private void pictureBox10_Click(object sender, EventArgs e)
{
if (pictureBox10.ImageLocation != @"icon1.png")
{
var image = Image.FromFile(@"icon1.png");
pictureBox10.Image = image;
pictureBox10.ImageLocation = @"icon1.png";
}
if (pictureBox10.ImageLocation == @"icon1.png")
{
var image = Image.FromFile(@"icon.png");
pictureBox10.Image = image;
pictureBox10.ImageLocation = @"icon.png";
}
}
您还需要更新初始属性设置以设置ImageLocation而不是Image属性,或者在设置Image文件的同时设置ImageLocation
编辑
首先,要设置属性,可以执行以下操作( Source ):
protected override void OnLoad(EventArgs e){
pictureBox10.ImageLocation = @"icon.png";
}
虽然我不记得是否可以创建PictureBox,否则,请使用onShown事件代替( Source )
编辑2
这是创建事件和设置属性的另一种方法,首先按照此处的步骤将事件onShown添加到表单。 您需要单击表单本身,而不是单击表单内部的控件才能找到事件。
完成后,在事件内添加以下代码:
pictureBox10.ImageLocation = @"icon.png";
那应该有助于解决您的问题
非常感谢每个人,但是还是有一些问题,但是已经解决了这个问题,所以请编写实际的代码...
public Form1()
{
InitializeComponent();
pictureBox10.ImageLocation = @"icon.png";
}
private void pictureBox10_Click(object sender, EventArgs e)
{
if (pictureBox10.ImageLocation == @"icon1.png")
{
pictureBox10.ImageLocation = @"icon.png";
}
else
{
pictureBox10.ImageLocation = @"icon1.png";
}
}
首先,您必须初始化图像的位置,然后使用两个if条件,我认为这是主要问题,否则无论如何都要每一个thak都给@Draken设置很多thak。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.