首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

Effective C# 原則 38:擁抱資料繫結,告別手動 UI 同步代碼

     編輯:關於C#

傳統 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");

資料來源內部追蹤狀態,控制項自動更新顯示,零事件代碼。

資料物件不支援 UI 屬性?建立顯示專用包裝類別


// 核心資料結構(僅存儲)
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


// 錯誤:建立兩個 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");

Web Forms 同樣支援宣告式繫結


<asp:TextBox id="TextBox1" runat="server"
    Text="<%# src.Text %>"
    ForeColor="<%# src.ForegroundColor %>" />

DataSet/DataGrid 進階:動態新增計算欄


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 同步代碼,提升正確性與維護性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved