復合控件 通過組合現有控件(Label + Timer 等)快速構建可復用 UI 組件。本文手把手演示:創建控件庫專案、添加構成控件、暴露屬性/事件、設計器體驗、測試專案引用、調試輸出,全流程零遺漏。
TimeLabelMyCompany.Controls.TimeLabelUserControl1 → TimeLabel(構造函數同步改名)lblTimetimer,Interval = 1000、Enabled = falsepublic partial class TimeLabel : UserControl
{
public TimeLabel()
{
InitializeComponent();
}
// 僅讀:當前顯示的時間文本
public string LabelText => lblTime.Text;
// 讀寫:背景色
public Color LabelBackColor
{
get => lblTime.BackColor;
set => lblTime.BackColor = value;
}
// 可選:字體、前景色、格式化字符串等
public Font LabelFont
{
get => lblTime.Font;
set => lblTime.Font = value;
}
public string TimeFormat { get; set; } = "T"; // 長時間格式
}
private void TimeLabel_Load(object sender, EventArgs e)
{
timer.Enabled = true; // 啟動計時
}
private void timer_Tick(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString(TimeFormat);
OnTick(EventArgs.Empty); // 觸發對外事件
}
// 自定義事件:時間已更新
public event EventHandler Tick;
protected virtual void OnTick(EventArgs e)
{
Tick?.Invoke(this, e);
}
TestTimeLabelTimeLabel.dllTimeLabel 到 Form1,屬性窗口設置 LabelBackColor、LabelFontpublic Form1()
{
InitializeComponent();
timeLabel1.Tick += (s, e) => Debug.WriteLine(timeLabel1.LabelText);
}
運行測試專案,輸出窗口每秒打印一次當前時間,證明事件正常觸發、屬性正常暴露。
| 功能 | 實現要點 |
|---|---|
| 設計器圖標 | 項目屬性 → Resources → 添加 16x16 .bmp/png → 類上方 [ToolboxBitmap(typeof(TimeLabel), "Icon.bmp")] |
| 屬性分類/描述 | [Category("Appearance")] [Description("背景色")] [DefaultValue(typeof(Color), "Control")] |
| 屬性瀏覽器編輯器 | 複雜類型用 TypeConverter、UITypeEditor(如顏色選擇器、字體對話框) |
| 序列化控制 | [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] 控制內部控件屬性是否序列化到 .resx |
| 智能標籤 | 實現 IComponent、添加 DesignerActionList 實現右鍵快捷菜單 |