首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 元件繼承實戰:打造可拖曳排序、雙擊刪除的 TListBox2

     編輯:Delphi

過去習慣將所有邏輯塞進主表單單元,導致程式碼臃腫難維護。現採用「元件封裝」策略:將獨立功能抽離為可重用元件,哪怕只是微小的行為差異,也獨立成單元。

需求:增強版 ListBox

  • 支援項目拖曳排序
  • 雙擊刪除項目

完整元件實作 (ListBox2.pas)

unit ListBox2; 

interface

uses System.Classes, Vcl.Controls, Vcl.StdCtrls, System.Types; 

type 
  TListBox2 = class(TCustomListBox) 
  protected
    procedure DragOver(Source: TObject; X: Integer; Y: Integer; State: TDragState; var Accept: Boolean); override;
    procedure DblClick; override;
  public
    constructor Create(AOwner: TComponent); override;
    procedure DragDrop(Source: TObject; X: Integer; Y: Integer); override;
  end; 

implementation

{ TListBox2 }

constructor TListBox2.Create(AOwner: TComponent); 
begin 
  inherited; 
  DragMode := dmAutomatic; { 啟用自動拖放模式 }
end; 

procedure TListBox2.DblClick; 
begin 
  inherited; 
  Items.Delete(ItemIndex); { 雙擊刪除當前項目 }
end; 

procedure TListBox2.DragDrop(Source: TObject; X, Y: Integer); 
begin 
  inherited; 
  Items.Exchange(ItemIndex, ItemAtPos(Point(X,Y), True)); { 交換項目位置 }
end; 

procedure TListBox2.DragOver(Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); 
begin 
  inherited; 
  Accept := True; { 接受所有拖放操作 }
end; 

end.

使用測試

uses ListBox2; 

procedure TForm1.FormCreate(Sender: TObject); 
begin 
  with TListBox2.Create(Self) do 
  begin 
    Parent := Self; 
    Align := alLeft; 
    Items.CommaText := 'A,B,C,D,E,F,G'; 
  end; 
end;

設計哲學

  1. 繼承 TCustomListBox 而非 TListBox,避免繼承多餘的發布屬性
  2. 覆寫核心虛擬方法:DragOver、DragDrop、DblClick
  3. 建構函式預設行為:一行程式碼啟用自動拖放
  4. 零配置使用:建立實例即具備完整功能,符合「慣例優於配置」原則

這種「微元件」開發模式讓主表單單元保持乾淨,業務邏輯與 UI 行為清晰分離,大幅提升程式碼可維護性與重用性。

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