【问题标题】:Set onclick event at runtime in Delphi XE在 Delphi XE 运行时设置 onclick 事件
【发布时间】:2015-07-07 16:13:09
【问题描述】:

这里是第一次发帖,所以请原谅任何礼仪错误。

我正在 Delphi XE8 中创建一个多设备 (FMX) 应用程序,并且难以将事件处理程序分配给动态创建的按钮。我搜索了 StackOverflow 并找到了与 NotifyEvents 相关的答案,所以我遵循了这些答案中的建议 - 仍然没有运气。编译错误为“E2010 Incompatible types: 'TNotifyEvent' and 'Procedure'”。

我已经整理了一个带有编辑字段和静态 Hello 按钮的表单的简单测试用例,第二个按钮创建了一个 Goodbye 按钮并尝试为 OnClick 事件分配一个过程,但我仍然得到相同的结果错误。

据我所知,我已经遵循了使该过程与 TNotifyEvent 兼容的所有要求,但即使是这个基本示例也因相同的错误而失败。我正在用头撞墙,所以有人可以告诉我我做错了什么吗?

非常感谢。

unit Dynamic_Button_Test1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
  FMX.Controls.Presentation, FMX.Edit;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Hello: TButton;
    Create_GoodBye: TButton;
    procedure HelloClick(Sender: TObject);
    procedure Create_GoodByeClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure GoodbyeClick(Sender: TObject) ;
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

procedure TForm1.Create_GoodByeClick(Sender: TObject);
var
  New_Button : TButton ;
begin
New_Button := TButton.Create( Form1 );
New_Button.Parent := Form1 ;
New_Button.Text := 'Goodbye' ;
New_Button.Visible := True ;
New_Button.Margins.Left := 50 ;
New_Button.Margins.Right := 50 ;
New_Button.Margins.Bottom := 30 ;
New_Button.Height := 50 ;
New_Button.Align := TAlignLayout.Bottom ;

New_Button.OnClick := TForm1.GoodbyeClick ;
end;

procedure TForm1.HelloClick(Sender: TObject);
begin
Edit1.Text := 'Hello' ;
end;

procedure TForm1.GoodbyeClick(Sender: TObject);
begin
Edit1.Text := 'Goodbye' ;
end;

end.

【问题讨论】:

  • New_Button.OnClick := TForm1.GoodbyeClickNew_Button.OnClick := Form1.GoodbyeClick,或者只是New_Button.OnClick := GoodbyeClick

标签: delphi event-handling firemonkey


【解决方案1】:

VCL/FMX 事件处理程序在运行时绑定到特定对象。分配事件处理程序时,您需要将类类型名替换为对象指针。当稍后触发事件时,该对象将成为事件处理程序的 Self 指针:

New_Button.OnClick := Self.GoodbyeClick ;

或者简单地说:

New_Button.OnClick := GoodbyeClick ; // Self implicitly used

附带说明 - 创建 Button 时,该代码位于 TForm1 实例方法中,因此您应该使用 Self 对象指针而不是全局 Form1 对象指针:

New_Button := TButton.Create( Self );
New_Button.Parent := Self ;

【讨论】:

    猜你喜欢
    • 2014-08-15
    • 1970-01-01
    • 2011-07-28
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    相关资源
    最近更新 更多