Delphi自定义TTreeNode

时间:2012-04-04 15:53:50

标签: delphi treeview treenode

我正在尝试制作自定义的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';

请帮忙

1 个答案:

答案 0 :(得分:8)

您的代码存在的问题是,对AddChild的调用会导致树视图创建新节点。由于您没有告诉树视图创建子类的节点,因此它创建了一个普通的TTreeNode。然后当你试图把它投射到TCustomTreeNode时,世界就会结束。

您需要使用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方法来创建新节点。