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

Effective C# 原則 38:使用與支援資料繫結 (下)

     編輯:關於C語言

簡單屬性繫結範例

將文字方塊前景色繫結至資料來源屬性:

textBox1.DataBindings.Add("ForeColor", src, "ForegroundColor");

資料來源物件維護屬性值,控制項自動更新顯示,大幅減少手動事件處理。

Web Forms 同樣適用

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

封裝不支援繫結的資料結構

若 FinancialResults 結構缺乏 UI 格式屬性,可建立包裝型別:

public struct FinancialDisplayResults
{
    private FinancialResults _results;
    public FinancialResults Results { get { return _results; } }
    public Color ProfitForegroundColor
    {
        get { return _results.Profit >= 0 ? Color.Black : Color.Red; }
    }
    // 其他格式屬性...
}

繫結時使用同一資料來源:

textBox1.DataBindings.Add("Text", src, "Results.Profit");
textBox1.DataBindings.Add("ForeColor", src, "ProfitForegroundColor");
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved