用事件调用子窗体
今天学到了一个很有用的知识点,多个窗体调用子窗体时,让子窗体和父窗体降低耦合度。同时子窗体的修改还可以及时反馈到父窗体。代码如下:
为了实现这个例子,你需要准备2个窗口,一个叫MainForm,上面至少需要一个richTextBox,两个工具栏按钮。
另一个叫 MyDialog 的子窗口,上面有一个 textBox1,一个 Button,作为确定按钮。
//父窗体
private MyDialog m_dlg;
private void button1_Click(object sender, EventArgs e)
{
if (m_dlg == null)
{
m_dlg = new MyDialog(richTextBox1.Text);
m_dlg.MyTextBoxChanged += new EventHandler(m_dlg_textboxchanged);
m_dlg.FormClosed += new FormClosedEventHandler(m_dlg_closed);
m_dlg.Show(this);
}
else
{
m_dlg.Activate();
}
}
private void m_dlg_textboxchanged(object sender1, EventArgs e1)
{
richTextBox1.Text = m_dlg.TextBoxValue;
}
private void m_dlg_closed(object sender1, EventArgs e1)
{
m_dlg = null;
}
private void button1_Click(object sender, EventArgs e)
{
if (m_dlg == null)
{
m_dlg = new MyDialog(richTextBox1.Text);
m_dlg.MyTextBoxChanged += new EventHandler(m_dlg_textboxchanged);
m_dlg.FormClosed += new FormClosedEventHandler(m_dlg_closed);
m_dlg.Show(this);
}
else
{
m_dlg.Activate();
}
}
private void m_dlg_textboxchanged(object sender1, EventArgs e1)
{
richTextBox1.Text = m_dlg.TextBoxValue;
}
private void m_dlg_closed(object sender1, EventArgs e1)
{
m_dlg = null;
}
//子窗体
public event EventHandler MyTextBoxChanged;
public string TextBoxValue
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
public MyDialog(string param)
{
InitializeComponent();
TextBoxValue = param;
}
private void button1_Click(object sender, EventArgs e)
{
if (MyTextBoxChanged != null)
{
MyTextBoxChanged(this, e);
}
}