首页 > 解决方案 > 在父窗体中访问子窗体继承的控件

问题描述

我使用德尔福 XE3。我有两种形式,TParentForm 和 TChildForm。TParentForm 包含 Button1,TChildForm 继承自它。

那么当我在TParentForm 中操作Button1 时,在下面的过程TParentFrm.Button2Click(Sender: TObject)中,当我调用ChildForm.Show 并单击Button1 时,它是对ChildForm 中Button1 的实例进行操作吗?

type
  TParentFrm = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  TChildForm = class(TParentFrm)
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  ParentFrm: TParentFrm;

implementation

{$R *.dfm}

procedure TParentFrm.Button2Click(Sender: TObject);
begin
  Button1.Caption := '&Test';  // Is it operating on Childform's button1 when I
                               // create and show child form and then click 
                               //"Button2".
end;

Test unit:

procedure TForm1.Button1Click(Sender: TObject);
begin
      ChildForm.Show;
end;


标签: delphi

解决方案


简短的回答:您的代码将更改与您单击的 Button2 相同的表单实例上的 Button1 控件的标题。


长答案:当您使用代码时Button1.Caption := '&Test';,您基本上指示计算去查找名为的组件Button1并将其Caption属性更改为&Test. 当计算机执行此搜索时,它总是在调用代码的表单实例中执行此操作。

因此,如果您的代码是从放置在您的按钮触发的 OnClick 事件中调用的,ParentForm它将影响Button1您的ParentForm.

如果代码是从您的按钮触发的 OnClick 事件中调用的ChildForm,它将影响Bu8tton1您的子表单上的事件。

是的,此时您的应用程序有两个名为 的按钮Button1。一个在你身上ParentForm,另一个在你身上ChildForm

事实上,您也可以创建另一个您的实例,ParentForm然后单击Button2 该表单将影响该Button1表单的实例,而不是您的原始实例ParentForm

我希望我的解释是可以理解的。如果没有,请告诉我。


推荐阅读