文章首發於 碼友網 -- 《再談C# Winforms桌面應用程序實現跨窗體間委託傳值(實例)》
前言
關於C# Winforms桌面應用程序跨窗體傳值其實是一個老生常談的問題了。我之前在碼友網也寫過多篇C# Winforms桌面應用程序跨窗體傳值的實例文章,比如:
《C# WINFORM窗體間通過委託和事件傳值(自定義事件參數)--實例詳解》
《C#/.NET WINFORM中使用委託和事件在類中更新窗體UI控件》
那為什麼還要“再談”C# Winforms桌面應用程序跨窗體委託傳值呢?因為對於絕大多數C#&.NET新手來説,要學習並熟練掌握C#的委託,事件等是比較難的知識點,需要開發者不斷地學習和項目實踐。
並且,實現C# Winforms窗體間傳值的方案也並不止一種,本文將為C#&.NET開發者們演示使用一種特殊的委託(delegate)--Action來實現的跨窗體傳值實例。
效果預覽
本實例主要演示的是聯繫人管理,其中包括新建聯繫人,聯繫人列表等功能。
實例的最終預覽效果如下:
創建解決方案及項目
打開Visual Studio 2022,創建一個用於測試的解決方案,命名為:WindowsFormsApp1,再在解決方案中創建名為WindowsFormsApp1的項目。
分別新建三個Winform窗體:FrmMain,FrmCreate,FrmList 和一個聯繫人的類Contact.cs
聯絡人類(Contact.cs)定義如下:
using System;
namespace WindowsFormsApp1.Models
{
/// <summary>
/// 聯繫人
/// </summary>
public class Contact
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
}
主窗體FrmMain.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using WindowsFormsApp1.Models;
namespace WindowsFormsApp1
{
public partial class FrmMain : Form
{
private List<Contact> _contacts;
public FrmMain()
{
_contacts = new List<Contact>();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var frm = new FrmCreate();
frm.OnContactCreated = (contact) =>
{
_contacts.Add(contact);
};
frm.ShowDialog();
}
private void button2_Click(object sender, EventArgs e)
{
var frm = new FrmList(_contacts);
frm.ShowDialog();
}
}
}
在主窗體,【新建聯繫人】按鈕事件中,創建了FrmCreate的實例frm,同時為frm實例設置了回調(委託)OnContactCreated,這一步是委託傳值的關鍵。
新建聯繫人窗體 FrmCreate.cs
using System;
using System.Windows.Forms;
using WindowsFormsApp1.Models;
namespace WindowsFormsApp1
{
public partial class FrmCreate : Form
{
public FrmCreate()
{
InitializeComponent();
}
/// <summary>
/// 聯繫人創建成功的回調(委託)
/// </summary>
public Action<Contact> OnContactCreated;
private void btnSubmit_Click(object sender, EventArgs e)
{
var contact = new Contact
{
Id = Guid.NewGuid(),
Name = textBox1.Text.Trim(),
Email = textBox2.Text.Trim()
};
OnContactCreated?.Invoke(contact);
Close();
}
}
}
在【新建聯繫人】窗體中,我們定義了聯繫人創建成功的回調(委託),當點擊“保存聯繫人”按鈕後,如果調用者設置了OnContactCreated回調,則會執行回調中的方法。其中,語句OnContactCreated?.Invoke(contact);是關鍵。
聯繫人列表窗體 FrmList.cs
using System.Collections.Generic;
using System.Windows.Forms;
using WindowsFormsApp1.Models;
namespace WindowsFormsApp1
{
public partial class FrmList : Form
{
private List<Contact> _contacts;
public FrmList(List<Contact> contacts)
{
_contacts = contacts;
InitializeComponent();
}
private void FrmList_Load(object sender, System.EventArgs e)
{
dataGridView1.DataSource = _contacts;
}
}
}
如果你對本演示的源碼感興趣,請至原文獲取。