0%

C#子窗口调用父窗口控件的委托实现

有时子窗体的操作需要实时调用父窗体中的控件操作,比如在父窗体的文本框中显示子窗体中的输出:

主窗体:

MainForm.cs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public partial class MainForm : Form  
{
public MainForm()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
SubForm SubForm = new SubForm();

// 3.将ChangeTextVal加入到委托事件中
// 等效于:
// SubForm.ChangeTextVal += ChangeTextVal;
SubForm.ChangeTextVal += new DelegateChangeTextVal(ChangeTextVal);
SubForm.ShowDialog();
}

public void ChangeTextVal(string TextVal)
{
this.textBox1.Text = TextVal;
}
}

子窗体:

SubForm.cs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 1.定义委托类型  
public delegate void DelegateChangeTextVal(string TextVal);

public partial class SubForm : Form
{
// 2.定义委托事件
public event DelegateChangeTextVal ChangeTextVal;

public SubForm()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
ChangeMainFormText(this.textBox1.Text);
}

private void ChangeMainFormText(string TextVal)
{
// 4.调用委托事件函数
ChangeTextVal(TextVal);
}
}