动态添加事件

时间:2012-05-14 07:37:35

标签: windows winforms events dynamic picturebox

我有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);
        }
    }
}

我找不到这个错误;请帮帮我。

2 个答案:

答案 0 :(得分: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;
    }
}

创建此类,编译应用程序并将这些自定义图片框从工具箱拖到表单中。当鼠标悬停在图片框上时,它们都将显示边框。

答案 1 :(得分:1)

我认为错误在于:

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

在这种情况下,

发件人将成为窗口。我认为您打算控制

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