在事件发生时注册要调用的方法的方法
我有一个包含20个PictureBox控件的Panel。 如果用户点击任何控件,我想要调用Panel中的方法。
我该怎么做呢?
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( func ) { foreach ( Control c in Controls ) { c.Click += new EventHandler( func ); } } }
我如何实现RegisterFunction()
? 此外,如果有很酷的C#function可以使代码更优雅,请分享。
“函数指针”由C#中的委托类型表示。 Click
事件需要一个EventHandler
类型的委托。 因此,您只需将EventHandler
传递给RegisterFunction方法,并为每个Click事件注册它:
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控件时添加事件处理程序:
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 }
正如dtb所提到的,你肯定应该在创建每个PictureBox
分配EventHandler
。 另外,您可以使用lambda表达式来执行此操作。
上述就是C#学习教程:在事件发生时注册要调用的方法的方法分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!
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); } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/950046.html