本例效果圖:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls;
type
TForm1 = class(TForm)
TreeView1: TTreeVIEw;
procedure FormCreate(Sender: TObject);
procedure TreeVIEw1DragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure TreeVIEw1DragDrop(Sender, Source: TObject; X, Y: Integer);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
stream: TStream;
begin
TreeVIEw1.Align := alLeft;
stream := TMemoryStream.Create;
with TStringList.Create do begin
Add('一連長');
Add(' 一排長');
Add(' 一班長');
Add(' 戰士1');
Add(' 戰士2');
Add(' 戰士3');
Add(' 戰士4');
Add(' 二班長');
Add(' 三班長');
Add(' 二排長');
Add(' 三排長');
Add('二連長');
Add('三連長');
SaveToStream(stream);
Free;
end;
stream.Position := 0;
TreeVIEw1.LoadFromStream(stream);
stream.Free;
TreeVIEw1.DragMode := dmAutomatic; {允許自動拖放}
end;
{只允許拖動子節點}
procedure TForm1.TreeVIEw1DragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
begin
Accept := not TTreeVIEw(Source).Selected.HasChildren;
end;
procedure TForm1.TreeVIEw1DragDrop(Sender, Source: TObject; X, Y: Integer);
var
n1,n2: TTreeNode;
begin
if Sender=Source then
begin
n1 := TTreeVIEw(Sender).Selected; {源}
n2 := TTreeVIEw(Sender).DropTarget; {目標}
TreeVIEw1.Items.Insert(n2, n1.Text); {目標前插入}
n1.Delete; {刪除源}
end;
end;
end.