過去習慣將所有邏輯塞進主表單單元,導致程式碼臃腫難維護。現採用「元件封裝」策略:將獨立功能抽離為可重用元件,哪怕只是微小的行為差異,也獨立成單元。
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;
DragOver、DragDrop、DblClick這種「微元件」開發模式讓主表單單元保持乾淨,業務邏輯與 UI 行為清晰分離,大幅提升程式碼可維護性與重用性。