C#窗體間傳值方法匯總
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
最終效果,就是點(diǎn)主窗體的按鈕,更改子窗體picturebox的圖片: 新建項(xiàng)目,添加一個(gè)主窗體Form1和子窗體Form2,我們的任務(wù)是,在主窗體點(diǎn)擊按鈕控制子窗體的picturebox控件。 1、第一種方法:Form2子窗體代碼: namespace FormConnections { public partial class Form2 : Form { public Form2() { InitializeComponent(); }
//建立一個(gè)公共函數(shù)用來(lái)更改pictureBox1的圖片 public void SetPic() { pictureBox1.ImageLocation = "c#.jpg"; }
private void pictureBox1_Click(object sender, EventArgs e) { //點(diǎn)擊圖片清空,為了調(diào)試用 pictureBox1.Image = null; } } } Form1調(diào)用這個(gè)函數(shù)就可以了: namespace FormConnections { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
//實(shí)例化兩個(gè)子窗體 Form2 f2 = null;
private void Form1_Load(object sender, EventArgs e) { //打開(kāi)子窗體 f2 = new Form2(); f2.Show(); }
private void button2_Click(object sender, EventArgs e) { //執(zhí)行Form2的公共函數(shù) f2.SetPic(); } } } 2、第二種方法,用委托子窗體代碼不變,父窗體代碼: namespace FormConnections { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Form2 f2 = new Form2();
private void Form1_Load(object sender, EventArgs e) { //打開(kāi)子窗體 f2.Show(); }
private void button2_Click(object sender, EventArgs e) { //用委托去執(zhí)行子窗體的內(nèi)容 this.Invoke(new Action(() => { f2.SetPic(); })); } } } 3、第三種方法,用事件解決此類問(wèn)題父窗體代碼: namespace FormConnections { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
//定義綁定FORM2更改圖片操作的事件 public event EventHandler ChangeForm2Pic;
private void Form1_Load(object sender, EventArgs e) { Form2 f2 = new Form2(); //父窗體加載時(shí),實(shí)例化Form2,并綁定事件 ChangeForm2Pic += f2.ChangePicEvent; f2.Show(); }
private void button2_Click(object sender, EventArgs e) { //點(diǎn)擊按鈕,執(zhí)行事件 ChangeForm2Pic(this, new Form2.PicPathArg() { PicPath = "C#.jpg" }); } } } 子窗體代碼: namespace FormConnections { public partial class Form2 : Form { public Form2() { InitializeComponent(); }
//內(nèi)部函數(shù) void GoSetPic(string picpath) { pictureBox1.ImageLocation = picpath; }
internal void ChangePicEvent(object sender, EventArgs e) { //執(zhí)行事件時(shí),得到傳遞來(lái)的參數(shù) PicPathArg thepicpath = (PicPathArg)e; //執(zhí)行內(nèi)部函數(shù) this.GoSetPic(thepicpath.PicPath); }
public class PicPathArg : EventArgs { //傳遞主窗體的數(shù)據(jù)信息 public string PicPath { get; set; } }
private void pictureBox1_Click(object sender, EventArgs e) { //點(diǎn)擊圖片清空,為了調(diào)試用 pictureBox1.Image = null; } } } 該文章在 2023/5/22 11:17:58 編輯過(guò) |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |