| 控件類型 | 前綴 | 枚舉值 |
| TextBox | txt | CtlType.TextBox |
| DropDownList / ComboBox | drp / cmb | CtlType.DropDownList / ComboBox |
| Hidden | hdn | CtlType.Hidden |
| CheckBox | chk | CtlType.CheckBox |
核心輔助類雛形
public enum CtlType { TextBox, DropDownList, ComboBox, Hidden, CheckBox }
public class ControlHelper
{
public static readonly string[] PrefixTable = new string[5];
static ControlHelper()
{
PrefixTable[(int)CtlType.TextBox] = "txt";
PrefixTable[(int)CtlType.DropDownList] = "drp";
PrefixTable[(int)CtlType.ComboBox] = "cmb";
PrefixTable[(int)CtlType.Hidden] = "hdn";
PrefixTable[(int)CtlType.CheckBox] = "chk";
}
// 解析控件 ID 獲取屬性名
private static string ParseControlID(string id, CtlType type)
{
return id.Substring(PrefixTable[(int)type].Length); // 簡化版,實際需 Replace
}
}
實體示例
class User
{
public string Name { get; set; }
public string Pwd { get; set; }
}
// 對應控件:txtName, txtPwd
反射綁定核心邏輯
// 實體 → UI
public static void SetControlsValues(Control root, object entity)
{
foreach (Control c in GetAllControls(root))
{
CtlType type = GetControlType(c);
string propName = ParseControlID(c.Name, type);
PropertyInfo pi = entity.GetType().GetProperty(propName);
if (pi != null && pi.CanWrite)
pi.SetValue(entity, GetControlValue(c, type), null);
}
}
// UI → 實體
public static void GetControlsValues(Control root, object entity)
{
// 類似邏輯,調用 pi.GetValue 並設置控件
}
系列規劃
- 本文:約定命名、前綴表、反射綁定雛形。
- 統一 WinForm/WebForm 訪問接口 (
IControl + 適配器)。
- 完善
ControlHelper:獲取/設置/驗證/樣式/清空全套操作。
- Controller 模式實現邏輯與視圖分離。
- 上一篇文章: C# 統一獲取設置 UI 控件值(二):統一 WinForm/WebForm 控件訪問接口
- 下一篇文章: C# 窗體動畫顯示(三):完整代碼與 AnimateWindow 參數詳解
Copyright ©
程式碼之家 All Rights Reserved