简体   繁体   English

在Windows窗体中调用公共方法

[英]Calling a public method in Windows Forms

I have 1 MDI Form which contains 1 panel control, and 1 Form with 1 button which serves to make panel in MDI not visible. 我有1个MDI表单,其中包含1个面板控件,1个表单带有1个按钮,用于使MDI中的面板不可见。

Code in MDI Form: MDI表格中的代码:

    public void displayInit()
    {
        panel1.Visible = false;
    }

Code in Form1: Form1中的代码:

        private void button1_Click(object sender, EventArgs e)
    {
        displayInit();
    }

The Error is: The name 'displayInit' does not exist in the current context, Any advice please ? 错误是:当前上下文中不存在名称'displayInit',请问有什么建议吗?

Try referencing the parent (and cast it): 尝试引用父级(并将其强制转换):

((MyMDIForm)this.MDIParent).displayInit();

This probably isn't the best way to do it though. 这可能不是最好的方法。 Consider having the child form raise an event to the MDI parent. 考虑让子表单向MDI父项提出事件。 Separation of concerns. 关注点分离。

The method displayinit() is an instance method, so you need an instance to call it from 方法displayinit()是一个实例方法,因此您需要一个实例来调用它

MyMDIForm.displayInit();

when constructing the MDI Form keep a reference to it and use that reference when calling it's methods. 在构造MDI表单时,请保留对它的引用,并在调用它的方法时使用该引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM