【发布时间】:2013-05-19 23:42:26
【问题描述】:
我正在尝试将信息从子窗体传递给父窗体。我一直在使用我在论坛上找到的以下代码来帮助我:
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace childform
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 tempDialog = new Form2(this);
tempDialog.ShowDialog();
}
public void msgme()
{
MessageBox.Show("Parent Function Called");
}
}
}
Form2.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace childform
{
public partial class Form2 : Form
{
private Form1 m_parent;
public Form2(Form1 frm1)
{
InitializeComponent();
m_parent = frm1;
}
private void button1_Click(object sender, EventArgs e)
{
m_parent.msgme();
}
}
}
效果很好,一切都很好。麻烦的是,我的程序要求我在 tempDialog 中设置变量,从 Form 1,在 button1_Click 以外的方法中。但是,这些找不到 tempDialog 的实例,因为它在 button1_click 中。
另外,我不能将它移出方法(例如,移入类),因为“this”修饰符不引用 Form1...
有什么想法可以从 Form2 引用 Form1,反之亦然?使用此代码还是其他方式?
谢谢
【问题讨论】:
标签: c# wpf winforms function public