自定義控件的事件處理遵循 .NET 標準事件模式:定義委托 → 定義事件參數類 → 聲明事件 → 觸發事件 → 消費者訂閱處理。本文展示一個完整的新聞展示控件實現。
public class NewsEventArgs : EventArgs
{
public int NewsId { get; }
public string NewsTitle { get; }
public NewsEventArgs(int newsId, string newsTitle)
{
NewsId = newsId;
NewsTitle = newsTitle;
}
}
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace ClientControl
{
// 1. 定義委托
public delegate void NewsClickEventHandler(object sender, NewsEventArgs args);
public partial class NewsStage : Control
{
// 2. 定義事件
public event NewsClickEventHandler NewsClicked;
private Graphics _graphics;
private bool _isMouseOver;
private int _newsId;
private string _newsTitle;
private Color _mouseOverColor = Color.Empty;
public NewsStage()
{
InitializeComponent();
SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.UserPaint |
ControlStyles.DoubleBuffer, true);
// 3. 內部事件訂閱(控件自我管理)
this.Click += NewsStage_Click;
this.MouseMove += NewsStage_MouseMove;
this.MouseLeave += NewsStage_MouseLeave;
}
// 4. 設計器屬性支援
[Description("新聞 ID"), Category("Appearance")]
public int NewsId
{
get => _newsId;
set { _newsId = value; Invalidate(); }
}
[Description("新聞標題"), Category("Appearance")]
public string NewsTitle
{
get => _newsTitle;
set { _newsTitle = value; Invalidate(); }
}
[Description("鼠標懸停時文字顏色"), Category("Appearance")]
public Color MouseOverColor
{
get => _mouseOverColor;
set { _mouseOverColor = value; }
}
// 5. 事件觸發方法(受保護虛方法,支援繼承覆寫)
protected virtual void OnNewsClicked(NewsEventArgs e)
{
NewsClicked?.Invoke(this, e);
}
// 6. 內部事件處理
private void NewsStage_MouseMove(object sender, MouseEventArgs e)
{
_isMouseOver = true;
Invalidate();
}
private void NewsStage_MouseLeave(object sender, EventArgs e)
{
_isMouseOver = false;
Invalidate();
}
private void NewsStage_Click(object sender, EventArgs e)
{
if (_newsId >= 0 && !string.IsNullOrEmpty(_newsTitle))
{
var args = new NewsEventArgs(_newsId, _newsTitle);
OnNewsClicked(args); // 觸發對外事件
}
}
// 7. 自定義繪製
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Color textColor = _isMouseOver && _mouseOverColor != Color.Empty
? _mouseOverColor
: ForeColor;
TextRenderer.DrawText(e.Graphics, _newsTitle, Font,
ClientRectangle, textColor, TextFormatFlags.Left | TextFormatFlags.VerticalCenter);
}
protected override void Dispose(bool disposing)
{
if (disposing) _graphics?.Dispose();
base.Dispose(disposing);
}
}
}
public partial class MainForm : Form
{
private NewsStage _newsControl;
public MainForm()
{
InitializeComponent();
InitializeNewsControl();
}
private void InitializeNewsControl()
{
_newsControl = new NewsStage
{
Location = new Point(20, 20),
Size = new Size(300, 40),
NewsId = 1001,
NewsTitle = "重大新聞:C# 12 正式發布!",
MouseOverColor = Color.Blue,
Font = new Font("微軟正黑體", 12, FontStyle.Bold)
};
// 訂閱自定義事件
_newsControl.NewsClicked += NewsControl_NewsClicked;
this.Controls.Add(_newsControl);
}
private void NewsControl_NewsClicked(object sender, NewsEventArgs e)
{
MessageBox.Show($"新聞被點擊!\nID: {e.NewsId}\n標題: {e.NewsTitle}",
"事件觸發", MessageBoxButtons.OK, MessageBoxIcon.Information);
// 這裡可執行導航、彈窗、記錄日誌等業務邏輯
}
}
| 原則 | 實現方式 | 優勢 |
|---|---|---|
| EventArgs 封裝 | 繼承 EventArgs,攜帶業務數據 | 類型安全、擴展性強、符合框架規範 |
| 委托簽名 | (object sender, TEventArgs e) | 標準模式,支援多播、序列化、弱引用 |
| 觸發方法 | protected virtual OnEventName | 允許子類覆寫、攔截或擴展觸發邏輯 |
| 空條件調用 | Event?.Invoke(this, e) | 線程安全(單線程 UI)、簡潔無需 null 檢查 |
| 設計器屬性 | Description/Category/Browsable | 屬性網格顯示友善、支援設計時配置 |
// 在控件中添加 ICommand 支援
public ICommand ClickCommand
{
get => (ICommand)GetValue(ClickCommandProperty);
set => SetValue(ClickCommandProperty, value);
}
public static readonly DependencyProperty ClickCommandProperty =
DependencyProperty.Register(nameof(ClickCommand), typeof(ICommand),
typeof(NewsStage), new PropertyMetadata(null));
// 觸發時同時執行命令
protected virtual void OnNewsClicked(NewsEventArgs e)
{
NewsClicked?.Invoke(this, e);
ClickCommand?.Execute(e);
}
標準化的事件模式是 .HT 控件開發的基石。掌握「委托 → EventArgs → 事件 → 觸發 → 訂閱」完整鏈路,能構建出專業級、可重用、設計器友善的自定義控件。本文範例展示了從底層繪製到高層事件暴露的完整生命週期管理。