之前在学校的时候没有认真的学习winform的开发,现在就要狂补下了。
1、构造函数的方法:
不解释,先看代码:
public Form2(string msg) {
InitializeComponent();
label1.Text = msg;
}
然后再Form3中就添加一个textbox和一个button
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(textBox1.Text);
f2.Show();
}
2、定义一个公共属性,这个我就不测试了,以前是也有用过就是了(只是当时是用公共字段)
public string Msg{
get{
return textbox1.Text();
}
}
3、委托与事件传递
先定义一个类,具体先看代码:
public delegate void TextChangeHandler(string s);
public class CallObject
{
public string ResultValue = "";
public event TextChangeHandler SelTextChanged;
public void ChangeSelText(string s) {
if (SelTextChanged != null) {
SelTextChanged(s);
}
}
}
然后再子窗体添加一个构造函数,以接受结果对象:
public Form2(CallObject cov) : this() {
this.co = cov;
}
第三步:在父窗体创建子窗体,并订阅cResult事件:
private void button1_Click(object sender, EventArgs e)
{
CallObject co = new CallObject();
co.SelTextChanged+=new TextChangeHandler(EventResultChanged);
Form2 f2 = new Form2(co);
f2.ShowDialog();
textBox2.Text = "子窗体返回的值是:\r\n" + co.ResultValue;
}
private void EventResultChanged(string s) {
textBox1.Text = s;
}
最后,在子窗体中改变选择,通过CallBack传递给父窗体
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
co.ChangeSelText("A");
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
co.ChangeSelText("B");
}
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
co.ChangeSelText("C");
}
private void button1_Click(object sender, EventArgs e)
{
co.ResultValue = textBox1.Text;
Close();
}
ok