2

我正在尝试制作我的自定义 TTreeNode 类

例如

TCustomTreeNode = class(TTreeNode)
  private
  public
    Comment:string;
  end;

我在树视图中创建并添加节点,如下所示:

var
  NewCustomTreeNode:TCustomTreeNode;
begin
  NewCustomTreeNode:= TCustomTreeNode.Create(TreeView.Items);
  NewCustomTreeNode.Comment:='blqblq';
  TreeView.Items.AddChild(NewCustomTreeNode,'NodeText');

当我尝试访问自定义创建的树节点错误弹出。例如我这样做:

TCustomTreeNode(TreeNode).Comment:='asdadssadas';

请帮忙

4

1 回答 1

9

您的代码的问题是调用AddChild导致树视图创建一个新节点。而且由于您没有告诉树视图创建子类的节点,因此它创建了一个普通的TTreeNode. 然后,当您尝试将其转换为 aTCustomTreeNode时,世界就结束了。

您需要使用该OnCreateNodeClass方法来确保树视图能够创建新节点。像这样:

type
  TCustomTreeNode = class(TTreeNode)
  protected
    procedure Assign(Source: TPersistent); override;
  public
    Comment: string;
  end;

procedure TCustomTreeNode.Assign(Source: TPersistent);
begin
  if Source is TCustomTreeNode then
    Comment := TCustomTreeNode(Source).Comment;
  inherited;
end;


procedure TForm1.FormCreate(Sender: TObject);
var
  NewNode: TCustomTreeNode;
begin
  NewNode := TreeView1.Items.Add(nil, 'Node1') as TCustomTreeNode;
  NewNode.Comment := 'A comment';
  NewNode := TreeView1.Items.Add(nil, 'Node2') as TCustomTreeNode;
  NewNode.Comment := 'Another comment';
end;

procedure TForm1.TreeView1Click(Sender: TObject);
var
  Node: TCustomTreeNode;
begin
  Node := TreeView1.Selected as TCustomTreeNode;
  if Assigned(Node) then
    ShowMessage(Node.Comment);
end;

procedure TForm1.TreeView1CreateNodeClass(Sender: TCustomTreeView; var NodeClass: TTreeNodeClass);
begin
  NodeClass := TCustomTreeNode;
end;

我不能声称自己是世界上最伟大的 Delphi 树视图专家,但根据我的经验,您永远不会自己创建树节点。您应该始终调用其中一种AddXXX方法TTreeView.Items来创建新节点。

于 2012-04-04T16:00:08.197 回答