2012-05-14 120 views
0

我有n個圖片框。他們應該動態執行以下事件:動態添加事件

private void pictureBoxMouseHover(object sender, EventArgs e) 
{ 
    if (sender is PictureBox) 
    { 
     ((PictureBox)sender).BorderStyle = BorderStyle.FixedSingle; 
    } 
} 

private void pictureBoxMouseLeave(object sender, EventArgs e) 
{ 
    if (sender is PictureBox) 
    { 
     ((PictureBox)sender).BorderStyle = BorderStyle.None; 
    } 
} 

private void MainMaster_Load(object sender, EventArgs e) 
{ 
    foreach (var control in Controls) 
    { 
     if (sender is PictureBox) 
     { 
      PictureBox pb=new PictureBox(); 
      pb.Name = sender.ToString(); 
      pb.MouseHover += new System.EventHandler(this.pictureBoxMouseHover); 
      pb.MouseLeave += new System.EventHandler(this.pictureBoxMouseHover); 
     } 
    } 
} 

我找不到這個問題;請幫幫我。

回答

1

我認爲錯誤是在這裏:

foreach (var control in Controls) 
{ 
    if (sender is PictureBox) 

發件人在這種情況下將是窗口。我想你打算控制

foreach (var control in Controls) 
{ 
    if (control is PictureBox) 
2

dbaseman是對的,您在迭代控件時使用了錯誤的變量。

但是,如果你想這種行爲添加到所有圖片框的話,最好的解決辦法是創建自定義的圖片框,並簡單地放置在您的形式:

public class MyPictureBox : PictureBox 
{ 
    protected override void OnMouseHover(EventArgs e) 
    { 
     BorderStyle = BorderStyle.FixedSingle; 
     base.OnMouseHover(e); 
    } 

    protected override void OnMouseLeave(EventArgs e) 
    { 
     base.OnMouseLeave(e); 
     BorderStyle = BorderStyle.None; 
    } 
} 

創建這個類,編譯應用程序,並拖累這些自定義圖片框從工具箱到您的窗體。鼠標懸停在圖片框上時,它們都會顯示邊框。