有任何錯誤之處請多指正。
多個WinForm窗體之間需要進行資料的傳遞,如何進行傳遞,如何更好的進行傳遞。
窗體之間傳值有五種方式(重點說委托)
1.使用構造函數進行執行個體化時進行傳值(無demo);
2.使用Tag進行傳值(無demo);
3.使用靜态資源進行傳值(無demo);
4.通過屬性進行傳值(無demo);
5.通過委托進行傳值
委托和lambda、Action、Func在之後的委托與事件、Lambda表達式等均會進行講解。
委托demo:
說明:
Form1有一個Textbox和Button
Form2有一個TextBox和三個Button
//Form1中Button的Click事件
private void btnSend_Click(object sender, EventArgs e)
{
//擷取TextBox的值
string inputValue = textBox1.Text.Trim();
//建立窗體
Form2 demoFrom = new Form2();
//委托進行窗體傳值
demoFrom.GetValue= delegate() {
return inputValue; };
//委托進行擷取值
demoFrom.SendValue = delegate(string a) {
this.textBox1.Text=a;
};
//委托進行擷取并傳遞值
demoFrom.GetAndSend = delegate(string a) {
string formValue = this.textBox1.Text;
this.textBox1.Text = a;
return formValue;
};
//展示
demoFrom.Show();
}
//Form2的三個委托
public Func<string> GetValue;
public Action<string> SendValue;
public Func<string, string> GetAndSend;
private void btnGet_Click(object sender, EventArgs e)
{
textBox1.Text = this.GetValue();
}
private void btnSend_Click(object sender, EventArgs e)
{
textBox1.Text += "。。。發送,走你";
//不操作From進行From的TextBox的修改
this.SendValue(textBox1.Text);
}
private void btnGetAndSend_Click(object sender, EventArgs e)
{
this.textBox1.Text=this.GetAndSend("既擷取,又發送");
}
Effect Picture:
![這裡寫圖檔描述](https://img-blog.csdn.net/20170729215826672?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQva2FuZ194dWFu/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)