將文字方塊前景色繫結至資料來源屬性:
textBox1.DataBindings.Add("ForeColor", src, "ForegroundColor");
資料來源物件維護屬性值,控制項自動更新顯示,大幅減少手動事件處理。
<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");