c# – 从子类调用公共父函数
发布时间:2020-12-15 20:03:35 所属栏目:百科 来源:网络整理
导读:在我的Main方法中,我正在实例化UpdateDialog类,其中基于用户是否按下按钮,我需要从Main调用function1().这是代码: public partial class Main : Form{ public void function1() { doing_stuff_here(); } private void button1_Click(Object sender,EventArg
在我的Main方法中,我正在实例化UpdateDialog类,其中基于用户是否按下按钮,我需要从Main调用function1().这是代码:
public partial class Main : Form { public void function1() { doing_stuff_here(); } private void button1_Click(Object sender,EventArgs e) { var update = new UpdateDialog(); update.ShowDialog(); } } public partial class UpdateDialog : Form { private void button2_Click(object sender,EventArgs e) { //call here function1() from Main } } 我应该怎么做才能从部分类UpdateDialog中的Main调用function1()? LE:虽然Styxxy建议的方法似乎是正确的,但由于跨线程无效操作,它在我的应用程序中不能很好地工作,所以我最终使用了Cuong Le建议的委托解决方法. 解决方法
您必须在UpdateDialog表单中拥有Main表单的实例.正如你所说UpdateDialog是你的主窗体的子窗体,我想你在Main窗体中创建UpdateDialog并在那里做一个show.在显示该表单之前,您可以分配
Parent property.
var updateDialog = new UpdateDialog(); // Or use "UpdateDialog updateDialog = new UpdateDialog();" as people like Andreas Johansson don't like the "var" keyword // Do other stuff here as well updateDialog.Parent = this; // Or use Show() for non modal window updateDialog.ShowDialog(); 您收到错误ArgumentException:无法将顶级控件添加到控件中.现在可以通过两种方式解决此问题. >您可以在主窗体上将 您可以手动设置所有者: updateDialog.Owner = this; 或者您可以将其作为参数添加到 updateDialog.Show(this); // or updateDialog.ShowDialog(this); “完整”代码使这个: var updateDialog = new UpdateDialog(); // Do other stuff here as well updateDialog.Owner= this; updateDialog.ShowDialog(); // or use .Show() // or updateDialog.ShowDialog(this); // or use .Show(this) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |