我正在尝试制作自定义的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';
请帮忙
答案 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
方法来创建新节点。