我有一个TSpeedButton类型的自定义组件,其中定义了两个额外的属性:
CommentHeading: string;
CommentText: string;
我在设计时设置CommentHeading。
当按下速度按钮时,便会显示一条备忘录,其下方有一个按钮,用于保存其内容。处理此的过程:
procedure CustomSpeedButton1Click(Sender: TObject);
begin
Receiver := CustomSpeedButton1.Name; // possibly used to save the memo text back to this speedbuttons property after comments are submitted
ViewComments(CustomSpeedButton1.CommentTitle,CustomSpeedButton1.CommentText);
end;
而ViewComments过程本身:
procedure ViewComments(comment_caption:string; comment_text:string);
begin
label15.Hide; // label showing editing in progress, hidden until user begins typing
Button1.Enabled := false; // the button for saving the memo text, hidden until user begins typing
CommentsBox.Visible := true; // pop up the comment box at the bottom of the form
CommentsBox.Caption := 'Comments: ' + comment_caption;
CommentsMemo.Text := comment_text; // if there are existing comments assign them to memo
end;
备忘录的内容需要分配给自定义SpeedButton的CommentText属性。
我最初的想法是,可以在按下自定义SpeedButton时将组件名称传递给变量,然后在按下备注上的保存按钮时检索该名称,然后使用该名称将备注文本分配给speedbuttons CommentText属性。但是后来我意识到,要做到这一点,我必须使用某种case..of语句,检查每个可能的speedbutton名称,然后将备注值分配给它的属性,这似乎很可笑。
有没有更简单的方法将备忘录文本分配给打开备忘录的快速按钮?
最佳答案
最终,您要问如何告诉ViewComments
函数使用哪个按钮的属性。
您了解Sender
事件中OnClick
参数的作用吗?它告诉事件处理程序正在处理哪个对象的事件。它正恰好充当您要带给ViewComments
函数的角色。
这就是梅森的答案。而不是传递所有属性值,而是传递对象本身:
procedure ViewComments(CommentButton: TCustomSpeedButton);
然后从所有按钮的事件处理程序中调用它:
procedure TForm1.CustomSpeedButton1Click(Sender: TObject);
begin
ViewComments(CustomSpeedButton1);
end;
procedure TForm1.CustomSpeedButton2Click(Sender: TObject);
begin
ViewComments(CustomSpeedButton2);
end;
没有字符串,没有
case
语句,没有查找。那应该可以回答您的问题,但是您可以做得更好。还记得我之前说过的
Sender
参数吗?当某人单击第一个按钮时,该Sender
处理程序的OnClick
参数将是该按钮,因此我们可以这样重写第一个事件处理程序:procedure TForm1.CustomSpeedButton1Click(Sender: TObject);
begin
ViewComments(Sender as TCustomSpeedButton);
end;
您可以像这样重写第二个事件处理程序:
procedure TForm1.CustomSpeedButton2Click(Sender: TObject);
begin
ViewComments(Sender as TCustomSpeedButton);
end;
嗯他们是一样的。具有两个相同的功能很浪费,因此,请放弃其中一个功能,然后重命名另一个功能,这样就不会发出特定于按钮的声音:
procedure TForm1.CommentButtonClick(Sender: TObject);
begin
ViewComments(Sender as TCustomSpeedButton);
end;
然后设置两个按钮的
OnClick
属性以引用该事件处理程序。您不能仅通过双击对象检查器中的属性来执行此操作。您需要自己输入名称,从下拉列表中选择名称,或者在运行时分配事件属性:CustomSpeedButton1.OnClick := CommentButtonClick;
CustomSpeedButton2.OnClick := CommentButtonClick;
我也想鼓励您为控件使用更有意义的名称。
Label15
特别令人震惊。您怎么还记得第15个标签是表示正在进行编辑的标签?例如,将其命名为EditInProgressLabel
。