2009-09-08 55 views
1

有谁知道我可以怎么写“cardImage1.BorderStyle = BorderStyle.Fixed3D;”而不必明确声明“cardImage1”?用方法切换BorderStyle。 C#

我试图把它放到一个方法中,以便我不需要编写代码来在两个边框样式之间切换,当单击一个图片框时,每个单个图片框(有52个!)

eg对于目前每个盒子,我需要在其_click事件中具有以下内容。

 if (cardImage1.BorderStyle == BorderStyle.None) 
     { 
      cardImage1.BorderStyle = BorderStyle.Fixed3D; 
     } 
     else 
     { 
      cardImage1.BorderStyle = BorderStyle.None; 
     } 

回答

0

而不是创建每个图片框的处理程序,你可以写一个方法O句柄的点击次数为您的所有图片框:

protected void onClickHandler(object sender, EventArgs e) 
{ 
    if (((PictureBox)sender).BorderStyle == BorderStyle.None) 
    { 
     ((PictureBox)sender).BorderStyle = BorderStyle.Fixed3D; 
    } 
    else 
    { 
     ((PictureBox)sender).BorderStyle = BorderStyle.None; 
    } 

} 

你也可以写一个循环来遍历所有控件上形式和ATTAC HTHE事件处理程序,所有的图片框(如果; S可能在你的情况下)

// 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个图片框感兴趣的小组,然后代替迭代ov呃形式(this.Controls)的所有控件只遍历控制在面板(thePanelControl.Controls

+0

非常感谢大家,这个特殊的问题已经解决,他背后的想法将会在项目中再次使用。 你不知道我昨晚在这个晚上绞尽脑汁想了多久! – Windos 2009-09-08 19:09:38

+0

我只是很高兴我可以帮助:) – 2009-09-08 19:40:09

4

假设这是一个事件处理程序,你应该投的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的所有实例。

0

创建一个新的类型MyPictureBox和处理点击事件。将所有PictureBox替换为MyPictureBox

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; 
     } 
    } 
}