是否可以在事件处理程序中关闭一个表单,其中事件处理程序在一个类中?

时间:2012-12-09 09:39:46

标签: c# forms class event-handling

我还在学习OOP。我目前正在尝试制作电影票亭,点击你喜欢的电影海报的按钮。 Form1是主菜单形式,其中显示3个按钮,其名称如下movibutton1,movibutton2,movibutton3。因此,基本上我想在每次单击按钮时隐藏Form1,但按钮的事件处理程序位于另一个类中。我希望事件处理程序留在课堂上。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        buttonPosters();
    }
    private void buttonPosters()
    {
        derClassForForm1 classForm1 = new derClassForForm1();
        moviButton1.Click += new EventHandler(classForm1.movPosterClicked);
        moviButton2.Click += new EventHandler(classForm1.movPosterClicked);
        moviButton3.Click += new EventHandler(classForm1.movPosterClicked);
    }
}

public class derClassForForm1
{
    public void movPosterClicked(object sender, EventArgs e)
    {
        Button posterClick = (Button)sender;
        if (posterClick.Name.Equals("moviButton1"))
        {
            Mov1 movie = new Mov1();
            Form2 movPoster = new Form2(movie.movTitle(), movie.movSynop(),   movie.movImagesrc());
            movPoster.Show();
        }
        else if (posterClick.Name.Equals("moviButton2"))
        {
            Mov2 movie = new Mov2();
            Form2 movPoster = new Form2(movie.movTitle(), movie.movSynop(), movie.movImagesrc());
            movPoster.Show();
        }
        else if (posterClick.Name.Equals("moviButton3"))
        {
            Mov3 movie = new Mov3();
            Form2 movPoster = new Form2(movie.movTitle(), movie.movSynop(), movie.movImagesrc());
            movPoster.Show();
        }

        //wanted to have like a form.hide() here
    }
}

1 个答案:

答案 0 :(得分:0)

您可以向类derClassForForm1添加公共属性:

public Form ParentForm {get; set;}

然后您可以修改方法buttonPosters中的代码:

private void buttonPosters()
{
    derClassForForm1 classForm1 = new derClassForForm1();
    classForm1.ParentForm = this;
    moviButton1.Click += new EventHandler(classForm1.movPosterClicked);
    moviButton2.Click += new EventHandler(classForm1.movPosterClicked);
    moviButton3.Click += new EventHandler(classForm1.movPosterClicked);
}

这样你就可以在movPosterClicked

的末尾写下这样的东西
if(this.ParentForm != null)
{
     this.ParentForm.Hide();
}