[英]Method to register method to be called when event is raised
我有一個包含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( <function pointer> func )
{
foreach ( Control c in Controls )
{
c.Click += new EventHandler( func );
}
}
}
我如何實現RegisterFunction()
? 此外,如果有很酷的C#功能可以使代碼更優雅,請分享。
“函數指針”由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表達式來執行此操作。
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.