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

C# WinForms 開發復合控件完整教程—— 以自動顯示時間控件為例

     編輯:關於C#

復合控件 通過組合現有控件(Label + Timer 等)快速構建可復用 UI 組件。本文手把手演示:創建控件庫專案、添加構成控件、暴露屬性/事件、設計器體驗、測試專案引用、調試輸出,全流程零遺漏。

一、專案創建與命名規範

  1. VS → 新建項目 → Windows Forms 控件庫 → 名稱 TimeLabel
  2. 命名空間改為 MyCompany.Controls.TimeLabel
  3. 類名 UserControl1 → TimeLabel(構造函數同步改名)

二、設計器添加構成控件

  • 工具箱雙擊 Label → 命名 lblTime
  • 工具箱雙擊 Timer → 命名 timer,Interval = 1000、Enabled = false

三、暴露屬性(封裝內部控件)

public 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"; // 長時間格式
}

四、核心邏輯:Timer Tick 更新時間 + 觸發自定義事件

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);
}

五、測試專案引用與使用

  1. 方案右鍵 → 添加 → 新建項目 → Windows Forms 應用程序 → TestTimeLabel
  2. 工具箱右鍵 → 選擇項目 → .NET Framework 組件 → 瀏覽 → 選中 TimeLabel.dll
  3. 拖放 TimeLabel 到 Form1,屬性窗口設置 LabelBackColor、LabelFont
  4. 訂閱事件:
    public Form1()
    {
        InitializeComponent();
        timeLabel1.Tick += (s, e) => Debug.WriteLine(timeLabel1.LabelText);
    }

六、調試輸出驗證

運行測試專案,輸出窗口每秒打印一次當前時間,證明事件正常觸發、屬性正常暴露。

七、進階強化清單

八、部署與版本管理

  • 發布 NuGet 包:nuget pack TimeLabel.nuspec,含 lib/net472/TimeLabel.dll、lib/net6.0-windows/TimeLabel.dll
  • 強名簽名:專案屬性 → 簽名 → 勾選「為程序集簽名」
  • 版本號:AssemblyVersion / AssemblyFileVersion 遵循 SemVer

九、總結

復合控件 = UserControl 容器 + 構成控件私有字段 + 公共屬性/事件封裝。關鍵原則:內部控件保持 private,只暴露必要屬性/事件,保證封裝性與安全性。掌握本文流程,即可將任何重複 UI 模式封裝為專業級復合控件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
功能實現要點
設計器圖標項目屬性 → Resources → 添加 16x16 .bmp/png → 類上方 [ToolboxBitmap(typeof(TimeLabel), "Icon.bmp")]
屬性分類/描述[Category("Appearance")] [Description("背景色")] [DefaultValue(typeof(Color), "Control")]
屬性瀏覽器編輯器複雜類型用 TypeConverter、UITypeEditor(如顏色選擇器、字體對話框)
序列化控制[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] 控制內部控件屬性是否序列化到 .resx
智能標籤實現 IComponent、添加 DesignerActionList 實現右鍵快捷菜單