如何为大量控件动态添加事件?

How to dynamically add events to a large number of controls?

我正在尝试将 1152 small pictureBoxes 添加到 Winform 动态然后我想为每个图片框添加一个 Click 事件,这样当我点击它们时,图像就会改变。我不知道如何添加事件处理程序!?

private void Form1_Load(object sender, EventArgs e)
{
        Image image1= Image.FromFile(@"C:\Users\image1.png");
        Image image2= Image.FromFile(@"C:\Users\image2.png");


        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                var pictures= new PictureBox
                {
                    Name = "pic" + i + j,
                    Size = new Size(14, 14),
                    Location = new Point(j * 14, i * 14),
                    Image = image1,
                };
                this.Controls.Add(pictures);
            }
         }
}

在事件处理程序的方法中,sender 参数将是您的 PictureBox 对象,因此您可以这样写:

private void Pb_Click(object sender, EventArgs e)
{
    PictureBox pb = sender as PictureBox;
    try
    {
        if (pb != null)
            pb.Image = Image.FromFile(@"NewImagePath");

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

所以你有一个图片框序列,你想要两件事:

  • 您想订阅点击事件
  • 如果 Click 事件发生您想要更改图像,可能取决于被单击的图片框。

首先,您需要有一系列您希望具有此行为的 PictureBoxes。如果您还没有一个序列,并且您希望某个控件上的所有 PictureBox 都有这种行为,您可以使用这个:

IEnumerable<PictureBox> GetPictureBoxes(Control control)
{
     return control.Controls.OfType<PictureControl>();
}

Enumerable.OfType

订阅活动:

IEnumerable<PictureBox> myPictureBoxes = ... 
foreach (PictureBox pictureBox in myPictureBoxes)
{
    pictureBox.Click += new System.EventHandler(this.pictureBox_Click);
}

事件处理程序:

private void pictureBox1_Click(object sender, EventArgs e)
{
    PictureBox pictureBox = (PictureBox)sender;

    Image imageToShow = DecideWhichImageToShow(pictureBox); // TODO
    // change the image:
    pictureBox.Image = imageToShow
}