[英]Toggle BorderStyle with a method. C#
有谁知道我怎么写“cardImage1.BorderStyle = BorderStyle.Fixed3D;” 无需明确声明“cardImage1”?
我正在尝试将它放入一个方法中,这样我就不需要编写代码来在两个边框样式之间切换时,单击一个图片框,每个单个图片框(有52个!)
例如,对于目前我需要在其_click事件中拥有以下内容的每个框。
if (cardImage1.BorderStyle == BorderStyle.None)
{
cardImage1.BorderStyle = BorderStyle.Fixed3D;
}
else
{
cardImage1.BorderStyle = BorderStyle.None;
}
假设这是在事件处理程序中,您应该将sender
参数转换为PictureBox
并直接对其进行操作。
private void pictureBox_Click(object sender, EventArgs args)
{
var image = (PictureBox)sender;
if (image.BorderStyle == BorderStyle.None)
{
image.BorderStyle = BorderStyle.Fixed3D;
}
else
{
image.BorderStyle = BorderStyle.None;
}
}
然后,您将在PictureBox
所有实例上使用相同的事件处理程序。
您可以编写一个方法来处理所有图片框的点击,而不是为每个图片框创建处理程序:
protected void onClickHandler(object sender, EventArgs e)
{
if (((PictureBox)sender).BorderStyle == BorderStyle.None)
{
((PictureBox)sender).BorderStyle = BorderStyle.Fixed3D;
}
else
{
((PictureBox)sender).BorderStyle = BorderStyle.None;
}
}
您还可以编写一个循环来遍历表单上的所有控件,并将事件处理程序附加到所有图片框(如果是这样;在您的情况下可能)
// in your form load event do something like this:
foreach(Control c in this.Controls)
{
PictureBox pb = c as PictureBox;
if(pb != null)
pb.Click += new EventHandler(onClickHandler); // where onClickHandler is the above function
}
当然,如果你在表格上有其他图片框,解决方案是将你感兴趣的52个图片框放在一个面板中,然后代替迭代表格中的所有控件( this.Controls )只迭代控件在面板中( thePanelControl.Controls )
创建一个新类型MyPictureBox
并处理click事件。 用MyPictureBox
替换所有PictureBox
。
class MyPictureBox : PictureBox
{
protected void this_Click(object sender, EventArgs e)
{
if (this.BorderStyle == BorderStyle.None)
{
this.BorderStyle = BorderStyle.Fixed3D;
}
else
{
this.BorderStyle = BorderStyle.None;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.