要实现子窗体与父窗体之间的通讯
有多种方法(比如
重载子窗体的构造函数
将父窗体的引用作为参数传递给子窗体)
下面我要介绍的是利用自定义事件的方法
它能够最大程度的避免模块之间的耦合
充分体现面向对象的优点
先将效果图展示给大家
[[The No Picture]]下面是实现代码
Unit //子窗体
type
//声明自定义事件的类型(类似于C#中的委托)
TMyEventHandle = procedure (Sender: TObject; Content: string) of object;
TForm = class(TForm)
ComboBox: TComboBox;
Label: TLabel;
procedure ComboBoxClick(Sender: TObject);
private
FOnSelectionChanged: TMyEventHandle;
public
//声明自定义事件
property OnSelectionChanged: TMyEventHandle
read FOnSelectionChanged write FOnSelectionChanged;
end;
procedure TFormComboBoxClick(Sender: TObject);
begin
//当选择改变时触发自定义的事件
if Assigned(FOnSelectionChanged) then
FOnSelectionChanged(Self ComboBoxText);
end;
Unit //父窗体
type
TForm = class(TForm)
btnOpenForm: TButton;
Edit: TEdit;
Label: TLabel;
procedure btnOpenFormClick(Sender: TObject);
private
m_frm: TForm;
procedure frm_SelectionChanged(Sender: TObject; Content: string);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
constructor TFormCreate(AOwner: TComponent);
begin
inherited Create(AOwner);
m_frm := TFormCreate(Self);
//指定当m_frm的自定义事件发生时的处理程序
m_frmOnSelectionChanged := frm_SelectionChanged;
end;
destructor TFormDestroy;
begin
m_frmFree;
inherited Destroy;
end;
procedure TFormfrm_SelectionChanged(Sender: TObject; Content: string);
begin
EditText := Content;
end;
procedure TFormbtnOpenFormClick(Sender: TObject);
begin
m_frmShowModal;
end;