将变量传递给.NET中的事件

时间:2011-01-31 17:17:11

标签: c# events

例如,我有一个图片框列表,一旦光标悬停在它们上面就会引发事件。 然而,我不仅需要以某种方式提升此事件,还要传递“i”变量,以便我知道哪个图片框上有光标。

for (int i = 0; i < 25; i++)
{
....
pbList.Add(new PictureBox());

pbList[i].MouseHover += new System.EventHandler(this.beeHideInfo);
                                            //// need to pass "i" here
}

    private void beeShowInfo(object sender, EventArgs e)
    {
        lb_beeInfo.Text = "You are hovering over: "+beeList[i].name;
                                               /// need to get this "i"
    }

有什么想法吗?

6 个答案:

答案 0 :(得分:5)

您无法将变量传递给事件。

此外,必要的变量已经传递给您:sender

sender是对引发事件的对象的引用。在您的情况下,它是引发事件的PictureBox的引用。

答案 1 :(得分:3)

object sender参数 发送事件的PictureBox。如果您需要将某些内容与该对象关联,则可以使用其Tag成员:

for (int i = 0; i < 25; i++)
{
    ....
    pbList.Add(new PictureBox() { Tag = beeList[i] });
    pbList[i].MouseHover += new System.EventHandler(this.beeHideInfo);
}

private void beeShowInfo(object sender, EventArgs e)
{
    PictureBox pb = (PictureBox)sender;
    Bee b = (Bee)pb.Tag;
    lb_beeInfo.Text = "You are hovering over: "+b.name;
}

答案 2 :(得分:2)

假设pbList和beelist包含相同顺序的相关项,您可以执行beeList[ pbList.IndexOf(sender) ].name

之类的操作

答案 3 :(得分:1)

你可以这样做:

for (int i = 0; i < 25; i++)
{
    ...

    pbList.Add(new PictureBox());

    var index = i;
    pbList[i].MouseHover += 
        delegate
        {
            lb_beeInfo.Text = "You are hovering over: "+beeList[index].name;
        };
}

即。使用匿名方法。

正如John Saunders所说,有一个更简单的解决方案。

答案 4 :(得分:1)

最简单的方法是使用匿名函数将PictureBox或索引实例显式传递给处理程序。

for (int i = 0; i < 25; i++)
{
  ....
  var box = new PictureBox();
  pbList.Add(box);
  box.MouseHover += delegate { this.beeShowInfo(box); }
}

private void beeShowInfo(PictureBox box) 
{
   lb_beeInfo.Text = "You are hovering over: "+box.Name;
}

答案 5 :(得分:1)

另一种方法可能是创建自定义图片框

class CustomPictureBox : PictureBox
{
  public int id;
  public CustomPictureBox(int ID)
 {
   id = ID;
 }

}

将一个GLOBAL id放到父级,每次单击CustomPicureBox获取ID 比你想要改变Clicked CustomPicutreBox测试它的地方

foreach(CustomPicutreBox i in Control.controls)
{
  if(i.ID == sender.ID)
  doWhatEveryYouWant(); 
}
}