Method registration method that will be called when an event occurs

I have a panel containing 20 PictureBox controls. If the user clicks on any control, I want the called method to be called in the panel.

How to do it?

public class MyPanel : Panel
{
   public MyPanel()
   {
      for(int i = 0; i < 20; i++)
      {
         Controls.Add(new PictureBox());
      }
   }

   // DOESN'T WORK.
   // function to register functions to be called if the pictureboxes are clicked.
   public void RegisterFunction( <function pointer> func )
   {
        foreach ( Control c in Controls )
        {
             c.Click += new EventHandler( func );
        }
   }
}

How to implement RegisterFunction()? Also, if there are cool C # features that can make the code more elegant, share it.

+3
source share
2 answers

A "function pointer" is represented by a delegation type in C #. The event Clickexpects a delegate of type EventHandler. Therefore, you can simply pass EventHandlerthe RegisterFunction method and register it for each Click event:

public void RegisterFunction(EventHandler func)
{
    foreach (Control c in Controls)
    {
         c.Click += func;
    }
}

Using:

public MyPanel()
{
    for (int i = 0; i < 20; i++)
    {
        Controls.Add(new PictureBox());
    }

    RegisterFunction(MyHandler);
}

, EventHandler , PictureBox ( ). , , , PictureBox:

public MyPanel()
{
    for (int i = 0; i < 20; i++)
    {
        PictureBox p = new PictureBox();
        p.Click += MyHandler;
        Controls.Add(p);
    }
}

, EventHandler, :

private void MyHandler(object sender, EventArgs e)
{
    // this is called when one of the PictureBox controls is clicked
}
+7

dtb, EventHandler PictureBox. , .

public MyPanel()
{
    for (int i = 0; i < 20; i++)
    {
        PictureBox p = new PictureBox();
        var pictureBoxIndex = i;
        p.Click += (s,e) =>
        {
            //Your code here can reference pictureBoxIndex if needed.
        };
        Controls.Add(p);
    }
}
0

Source: https://habr.com/ru/post/1748013/


All Articles