This is the case:
3 involucrated: a myComponent component, an ancestor form and a child form: (edited)
MyComponent:
unit Component1;
interface
uses
System.SysUtils, System.Classes, Vcl.Dialogs;
type
TMyComponent = class(TComponent)
private
{ Private declarations }
procedure Something(i: Integer);
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
published
{ Published declarations }
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TMyComponent]);
end;
{ TMyComponent }
constructor TMyComponent.Create(AOwner: TComponent);
var
i: integer;
begin
inherited Create(AOwner);
if AOwner.ComponentCount > 0 then
for i := 0 to AOwner.ComponentCount -1 do
Something(i);
end;
procedure TMyComponent.Something(i: Integer);
var
txt: string;
begin
txt := Format('Owner Name is %s, Owner Class is %s, ComponentCount is %d,'+
'myIndex is %d, My name is %s, my class is %s',
[Owner.Name, Owner.ClassName, Owner.ComponentCount, i, Owner.Components[i].Name,
Owner.Components[i].ClassName]);
ShowMessage('Hello '+txt);
end;
end.
The ancestor Form:
unit Ancestor;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Component1;
type
TmyAncestor = class(TForm)
MyComponent1: TMyComponent;
private
{ Private declarations }
public
{ Public declarations }
end;
var
myAncestor: TmyAncestor;
implementation
{$R *.dfm}
end.
The child Form:
unit TheChild;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Ancestor, Vcl.StdCtrls, Component1;
type
TmyChild = class(TmyAncestor)
edt1: TEdit;
private
{ Private declarations }
public
{ Public declarations }
end;
var
myChild: TmyChild;
implementation
{$R *.dfm}
end.
The dpr:
program InheritanceTest;
uses
Vcl.Forms,
Ancestor in 'Ancestor.pas' {myAncestor},
TheChild in 'TheChild.pas' {myChild};
{$R *.res}
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TmyChild, myChild);
Application.Run;
end.
The child Form inherits myComponent from the ancestor Form.
When created, the child Form triggers the TMyComponent.Create()
constructor, but AOwner.ComponentCount
see the ancestor ComponentCount
and not the child's ComponentCount
.
The message (from the myComponent.Something()
method) shows this:
"Hello Owner Name is myAncestor, Owner class is TMyChild, ComponentCount is 1, myIdex is 0, My name is , my class is TMyComponent"
The component does not see the edt1
component in the child form!!!
How can I see the correct ComponentCount?