Attaching an object to an already existing ListItem?

烈酒焚心 提交于 2019-12-06 10:46:18

You can access it through the TListItem.Data property. For example:

var
  ListItem: TListItem;
begin
  ListView1.AddItem('Item 1', nil);
  ...
  ListItem := ListView1.Items[0];
  ListItem.Data := Edit1;
  TEdit(ListItem.Data).Text := 'Updated text...';
end;

You could solve this using the Data property of TListItem. That's often a quick and easy approach. The only slight wrinkle is if you need the list items to manage the lifetime of their associated data. In that case you have to implement an OnDeletion event handler to finalize the associated data when a node is destroyed.

An alternative approach is to use a subclass of TListItem. First define your subclass:

type
  TMyListItem = class(TListItem)
  private
    FDateTime: TDateTime;
  public
    property DateTime: TDateTime read FDateTime write FDateTime;
  end;

Then implement a handler for the list view's OnCreateNodeClass event. This determines the actual class of list item that the list view instantiates.

procedure TForm1.ListView1CreateItemClass(Sender: TCustomListView; 
  var ItemClass: TListItemClass);
begin
  ItemClass := TMyListItem;
end;

Now the list view will create items of class TMyListItem.

So, you can simply access a list item's DateTime property as you would any other property. Of course this approach can be extended to store more information.

The only other point to make is that the list view control will still offer you items that are compile time typed as being TListItem. So you will need to up-cast.

For example, suppose you wanted to do something when an item was edited. The event handler looks like this:

procedure ListView1Edited(Sender: TObject; Item: TListItem; var S: string);

Note that the item is passed as type TListItem. So you would need to write it like this:

procedure TForm1.ListView1Edited(Sender: TObject; Item: TListItem; 
  var S: string);
var
  MyItem: TMyListItem;
begin
  MyItem := Item as TMyListItem;
  if MyItem.DateTime ....
end;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!