TCollectionItem represents an item in a collection.
Unit
Classes
Description
A TCollection holds a group of TCollectionItem objects. TCollectionItems are created and destroyed by TCollection抯 Add and Clear methods. Each TCollectionItem has a Collection property that points to the TCollection object to which the item belongs.
Objects descended from TCollection can contain objects descended from TCollectionItem. For example, a TDBGridColumns object contains TColumn objects; these two classes are used by TDBGrid to represent grid columns.
- TCollectionItem = class(TPersistent)
- private
- FCollection: TCollection;
- FID: Integer;
- function GetIndex: Integer;
- protected
- procedure Changed(AllItems: Boolean);
- function GetOwner: TPersistent; override;
- function GetDisplayName: string; virtual;
- procedure SetCollection(Value: TCollection); virtual;
- procedure SetIndex(Value: Integer); virtual;
- procedure SetDisplayName(const Value: string); virtual;
- public
- constructor Create(Collection: TCollection); virtual;
- destructor Destroy; override;
- function GetNamePath: string; override;
- property Collection: TCollection read FCollection write SetCollection;
- property ID: Integer read FID;
- property Index: Integer read GetIndex write SetIndex;
- property DisplayName: string read GetDisplayName write SetDisplayName;
- end;
- { TCollectionItem }
- constructor TCollectionItem.Create(Collection: TCollection);
- begin
- SetCollection(Collection);
- end;
- destructor TCollectionItem.Destroy;
- begin
- SetCollection(nil);
- inherited Destroy;
- end;
- procedure TCollectionItem.Changed(AllItems: Boolean);
- var
- Item: TCollectionItem;
- begin
- if (FCollection <> nil) and (FCollection.FUpdateCount = 0) then
- begin
- if AllItems then Item := nil else Item := Self;
- FCollection.Update(Item);
- end;
- end;
- function TCollectionItem.GetIndex: Integer;
- begin
- if FCollection <> nil then
- Result := FCollection.FItems.IndexOf(Self) else
- Result := -1;
- end;
- function TCollectionItem.GetDisplayName: string;
- begin
- Result := ClassName;
- end;
- function TCollectionItem.GetNamePath: string;
- begin
- if FCollection <> nil then
- Result := Format('%s[%d]',[FCollection.GetNamePath, Index])
- else
- Result := ClassName;
- end;
- function TCollectionItem.GetOwner: TPersistent;
- begin
- Result := FCollection;
- end;
- procedure TCollectionItem.SetCollection(Value: TCollection);
- begin
- if FCollection <> Value then
- begin
- if FCollection <> nil then FCollection.RemoveItem(Self);
- if Value <> nil then Value.InsertItem(Self);
- end;
- end;
- procedure TCollectionItem.SetDisplayName(const Value: string);
- begin
- Changed(False);
- end;
- procedure TCollectionItem.SetIndex(Value: Integer);
- var
- CurIndex: Integer;
- begin
- CurIndex := GetIndex;
- if (CurIndex >= 0) and (CurIndex <> Value) then
- begin
- FCollection.FItems.Move(CurIndex, Value);
- Changed(True);
- end;
- end;