c#:如何识别从哪个子窗体被按钮(属于一个parentForm)点击

本文关键字:属于 按钮 点击 parentForm 一个 窗体 何识别 识别 | 更新日期: 2023-09-27 18:03:37

我有4个ChildForm(1..4),其基类是ParentForm。

ParentForm有一个按钮。

是否有办法知道从哪个ChildForm是按钮实际点击?

c#:如何识别从哪个子窗体被按钮(属于一个parentForm)点击

控件有一个Parent或Page属性,您可以使用其中一个吗?

是的,稍加思考你就能做到。在事件处理程序中,用户使用sender对象来获取父对象的类型:

Type ChildFormType = ((Button)sender).Parent.GetType();

然而,不得不使用反射(查询类型系统)通常是糟糕设计的标志。某种访问者模式的实现,其中ParentForm作为一个抽象的accept方法可能是一个解决方案。

我知道你有4个不同的类为你的4个形式,所有从ParentForm派生。如果是这种情况,我将以这种方式实现ButtonClicked方法:

    private void button1_Click(object sender, EventArgs e)
    {
        // part common to all the forms (possibly void)
        specific_button1_Click(sender, e);
        // part common to all the forms (possibly void)
    }
    protected void specific_button1_Click(object sender, EventArgs e)
    {
    }
然后重写派生表单
中的specific_button1_Click方法