傳統 WinForms 開發需手寫大量「控制項↔物件」同步代碼,重複、易漏、難維護。.NET 資料繫結將物件屬性自動映射至控制項屬性,由 BindingManager 與 CurrencyManager 內部處理雙向傳輸。
// 單行取代一堆事件處理器
textBoxName.DataBindings.Add("Text", myDataValue, "Name");
需求:文字無效時顯示紅色。傳統做法需處理多個事件;資料繫結只需在資料物件新增 ForegroundColor 屬性:
public Color ForegroundColor => IsTextValid() ? Color.Black : Color.Red;
// 繫結
textBox1.DataBindings.Add("ForeColor", src, "ForegroundColor");
資料來源內部追蹤狀態,控制項自動更新顯示,零事件代碼。
// 核心資料結構(僅存儲)
struct FinancialResults {
public decimal Revenue { get; }
public decimal Profit => Revenue - Cost;
}
// 顯示包裝類別(含 UI 格式化)
struct FinancialDisplayResults {
private FinancialResults _results;
public FinancialResults Results => _results;
public Color ProfitForegroundColor => _results.Profit >= 0 ? Color.Black : Color.Red;
public bool SalaryBold => _results.Revenue < 100;
// ...
}
// 繫結同一資料來源不同屬性
textBox1.DataBindings.Add("Text", src, "Results.Profit");
textBox1.DataBindings.Add("ForeColor", src, "ProfitForegroundColor");
// 錯誤:建立兩個 BindingManager
textBox1.DataBindings.Add("Text", src.Results, "Profit");
textBox1.DataBindings.Add("ForeColor", src, "ProfitForegroundColor");
// 正確:同一資料來源
textBox1.DataBindings.Add("Text", src, "Results.Profit");
textBox1.DataBindings.Add("ForeColor", src, "ProfitForegroundColor");
<asp:TextBox id="TextBox1" runat="server"
Text="<%# src.Text %>"
ForeColor="<%# src.ForegroundColor %>" />
DataTable dt = data.Tables["Employees"];
dt.Columns.Add("EmployeeName", typeof(string), "lastname + ', ' + firstname");
SQL 運算式自動計算,繫結至 DataGrid 即時顯示。
Format:資料源→控制項,可自訂顯示格式;Parse:控制項→資料源,可捕獲轉換失敗並給予使用者回饋:
private void Form1_Parse(object sender, ConvertEventArgs e) {
try { Convert.ToInt32(e.Value); }
catch { MessageBox.Show($"{e.Value} 非整數"); e.Value = 0; }
}
專注於建立「描述顯示參數的資料類型」,其餘傳輸工作交給 WinForms/WebForms 資料繫結框架。大幅減少 UI 同步代碼,提升正確性與維護性。