Копировать узлы с поддеревом TTreeView во второй TTreeView

Материал из DRKB

Копировать узлы с поддеревом TTreeView во второй TTreeView[править | править код]

type
  {: Callback to use to copy the data of a treenode when the
    node itself is copied by CopySubtree.
  @param oldnode is the old node
  @param newnode is the new node
  @Desc Use a callback of this type to implement your own algorithm
    for a node copy. The default just uses the Assign method, which
    produces a shallow copy of the nodes Data property. }
  TCopyDataProc = procedure(oldnode, newnode: TTreenode);

{: The default operation is to do a shallow copy of the node, via Assign. }
procedure DefaultCopyDataProc(oldnode, newnode: TTreenode);
begin
  newnode.Assign(oldnode);
end;

{-- CopySubtree -------------------------------------------------------}
{: Copies the source node with all child nodes to the Target TTreeView.
@Param SourceNode is the node to copy
@Param Target is the treeview to insert the copied nodes into
@Param TargetNode is the node to insert the copy under, can be nil to
  make the copy a top-level node.
@Param CopyProc is the (optional) callback to use to copy a node.
  If Nil is passed for this parameter theDefaultCopyDataProc will be
used.
@Precondition  SourceNode <> nil, Target <> nil, TargetNode is either
  nil or a node of Target
@Raises Exception if TargetNode happens to be in the subtree rooted in
  SourceNode. Handling that special case is rather complicated, so we
  simply refuse to do it at the moment. }
{ Created 2003-04-09 by P. Below
-----------------------------------------------------------------------}
procedure CopySubtree(SourceNode: TTreenode; Target: TTreeView;
  TargetNode: TTreeNode; CopyProc: TCopyDataProc = nil);
var
  Anchor: TTreenode;
  Child: TTreenode;
begin { CopySubtree }
  Assert(Assigned(SourceNode), 'CopySubtree:sourcenode cannot be nil');
  Assert(Assigned(Target), 'CopySubtree: target treeview cannot be nil');
  Assert((TargetNode = nil) or (TargetNode.TreeView = Target),
    'CopySubtree: targetnode has to be a node in the target treeview.');

  if (SourceNode.TreeView = Target)
  and (TargetNode.HasAsParent(SourceNode)
  or (SourceNode = TargetNode)) then
    raise Exception.Create('CopySubtree cannot copy a subtree to one of the ' +
      'subtrees nodes.');

  if not Assigned(CopyProc) then
    CopyProc := DefaultCopyDataProc;

  Anchor := Target.Items.AddChild(TargetNode, SourceNode.Text);
  CopyProc(SourceNode, Anchor);
  Child := SourceNode.GetFirstChild;
  while Assigned(Child) do
  begin
    CopySubtree(Child, Target, Anchor, CopyProc);
    Child := Child.GetNextSibling;
  end;
end;


procedure TForm1.Button1Click(Sender : TObject);
begin
  if Assigned(TreeView1.Selected) then
    CopySubtree(TreeView1.Selected, TreeView2, nil);
end;


Source: Взято с сайта: http://www.swissdelphicenter.ch
ID: 01116