注册方法以在引发事件时调用 [英] Method to register method to be called when event is raised
问题描述
我有一个包含 20 个 PictureBox 控件的面板.如果用户单击任何控件,我希望调用 Panel 中的一个方法.
I have a Panel which contains 20 PictureBox controls. If a user clicks on any of the controls, I want a method within the Panel to be called.
我该怎么做?
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 );
}
}
}
如何实现RegisterFunction()
?另外,如果有很酷的C#特性可以让代码更优雅,请分享.
How do I implement RegisterFunction()
?
Also, if there are cool C# features that can make the code more elegant, please share.
推荐答案
函数指针"在 C# 中由委托类型表示.Click
事件需要 EventHandler
类型的委托.因此,您可以简单地将 EventHandler
传递给 RegisterFunction 方法并为每个 Click 事件注册它:
A "function pointer" is represented by a delegate type in C#. The Click
event expects an delegate of type EventHandler
. So you can simply pass an EventHandler
to the RegisterFunction method and register it for each Click event:
public void RegisterFunction(EventHandler func)
{
foreach (Control c in Controls)
{
c.Click += func;
}
}
用法:
public MyPanel()
{
for (int i = 0; i < 20; i++)
{
Controls.Add(new PictureBox());
}
RegisterFunction(MyHandler);
}
请注意,这会将 EventHandler
委托添加到 每个 控件,而不仅仅是 PictureBox 控件(如果有其他控件).更好的方法可能是在创建 PictureBox 控件时添加事件处理程序:
Note that this adds the EventHandler
delegate to every control, not just the PictureBox controls (if there are any other). A better way is probably to add the event handlers the time when you create the PictureBox controls:
public MyPanel()
{
for (int i = 0; i < 20; i++)
{
PictureBox p = new PictureBox();
p.Click += MyHandler;
Controls.Add(p);
}
}
EventHandler
委托指向的方法如下所示:
The method that the EventHandler
delegate points to, looks like this:
private void MyHandler(object sender, EventArgs e)
{
// this is called when one of the PictureBox controls is clicked
}
这篇关于注册方法以在引发事件时调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!