2010-06-01 70 views
3

我有一個包含20個PictureBox控件的面板。如果用戶點擊任何控件,我想調用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#功能可以使代碼更優雅,請分享。

+0

您是否只希望功能在面板內部的圖片框控件上單擊時發生? – msarchet 2010-06-01 17:25:42

回答

7

「函數指針」由C#中的委託類型表示。 Click事件需要EventHandler類型的代理。所以,你可以簡單地傳遞一個EventHandler到RegisterFunction方法,並將其註冊爲每次點擊事件:

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 
} 
0

由於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); 
    } 
} 
+2

請記住,lambda表達式捕獲變量'i',而不是變量'i'的值。 – dtb 2010-06-01 17:37:16

+0

@dtb是的,我已經更新以展示如何獲得價值。 – juharr 2010-06-01 17:39:13

相關問題