Attaching an object to an already existing ListItem?

那年仲夏 提交于 2019-12-10 11:02:18

问题


In a ListView, how can I attach an object at any time to an already existing ListItem? (I know I can attach an object to a ListItem with AddItem, however I need to attach the object after the ListItem has been created).


回答1:


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;



回答2:


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;


来源:https://stackoverflow.com/questions/14923332/attaching-an-object-to-an-already-existing-listitem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!