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

.NET 元件控件實戰系列 (二):Label 模擬超連結元件 - 滑鼠事件動態切換外觀

     編輯:關於.NET

動機

內建 LinkLabel 強制底線、僅能改連結色、無法改背景色。自製元件可完整自訂 Hover/Active/Visited 狀態的前景、背景、字型、底線等。

建立元件專案步驟

  1. 專案類型:類別庫 (最通用,可含元件/控件/表單)。
  2. 加入元件:方案總管右鍵 → Add → Component → 命名 SimulateLinkLabel。
  3. 加入參考:System.Drawing、System.Windows.Forms。
  4. 引入命名空間:using System.Drawing; using System.Windows.Forms; using System.ComponentModel;。

核心屬性設計

屬性說明
TargetLabel目標 Label,設定時自動解綁舊控件事件、綁定新控件
EnableHoverForeColor / HoverForeColor滑鼠進入前景色
EnableHoverBackColor / HoverBackColor滑鼠進入背景色
EnableActiveForeColor / ActiveForeColor滑鼠按下前景色
EnableActiveBackColor / ActiveBackColor滑鼠按下背景色

每個顏色屬性對應一個 EnableXxx 布林開關,預設 false,配合 DefaultValue(typeof(Color), "ColorName") 讓設計器正確序列化。

事件綁定與解綁


public Label TargetLabel
{
    get => m_TargetLabel;
    set
    {
        if (m_TargetLabel != value)
        {
            RemoveEventHandlers(); // 關鍵:避免多重綁定
            m_TargetLabel = value;
            AddEventHandlers();
        }
    }
}

void AddEventHandlers()
{
    if (m_TargetLabel != null && !DesignMode)
    {
        m_TargetLabel.MouseEnter += Label_MouseEnter;
        m_TargetLabel.MouseLeave += Label_MouseLeave;
        m_TargetLabel.MouseDown += Label_MouseDown;
        m_TargetLabel.MouseUp += Label_MouseUp;
    }
}

DesignMode 判斷:設計時不綁定事件,避免設計器誤觸發。

滑鼠事件處理邏輯


void Label_MouseEnter(...)
{
    if (item.Enabled)
    {
        // 備份原始樣式
        m_LabelForeColor = item.ForeColor;
        m_LabelBackColor = item.BackColor;
        m_LabelFont = item.Font;

        item.Cursor = Cursors.Hand;
        item.Font = new Font(m_LabelFont, m_LabelFont.Style | FontStyle.Underline); // 底線

        if (m_EnableHoverForeColor) item.ForeColor = m_HoverForeColor;
        if (m_EnableHoverBackColor) item.BackColor = m_HoverBackColor;
    }
}

void Label_MouseLeave(...) => 恢復備份的 ForeColor/BackColor/Font/Cursor;

void Label_MouseDown(...) => 啟用 Active 顏色;

void Label_MouseUp(...) => 根據 Hover 開關決定恢復 Hover 或原始顏色;

Font 不可變:需 new Font(...) 重建以加底線。

DefaultProperty 提升設計體驗


[DefaultProperty("TargetLabel")]
public class SimulateLinkLabel : Component { ... }

選中元件時屬性視窗自動聚焦 TargetLabel,加速設定。

類別圖

類別圖1

類別圖2

測試與擴充

  • 建立 WinForm 專案參考元件專案,工具箱自動出現 SimulateLinkLabel。
  • 拖放至表單,設定 TargetLabel 為表單上既有 Label。
  • F5 執行,體驗滑鼠進入/按下/離開的視覺回饋。
  • 可自行擴充 VisitedLinkColor (需記錄點擊狀態)、圖片切換等。

原始碼下載:https://www.bianceng.net/dotnet/201212/728.htm

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved