由于您希望正确完成 Caption 属性,因此 Mason 的答案将不起作用,因为他错过了“csSetCaption”的事情,并且他关于“default”的建议也不起作用,因为 Caption 和您的属性都是字符串类型。
以下是您想要的单位。
行为如下:
- Caption 属性的初始值为“Comments”
- 用户可以在设计时通过设置一个新值来覆盖它
(如果您不想要 2.,那么您需要像 Ken 提到的那样在覆盖的 Loaded 方法中分配 Caption 属性;但是,您的问题并不清楚您是否想要这样做。如果您这样做,请重新表述您的问题。 )
这就是代码的工作方式。
对于字符串属性,您不能提示任何default的流系统。但是您可以在构造函数中设置设计时的初始值:Caption := DefaultCustomSpeedButtonCaption;
对于 Caption 属性,您还必须禁用 Caption 属性的默认分配(否则您的组件将自动获得类似“CustomSpeedButton1”的标题)。此行为您执行此操作:ControlStyle := ControlStyle - [csSetCaption];
最后,最好将您的组件注册拆分为一个单独的单元。这允许您拥有一个在 IDE 中注册组件的设计时包和一个用于在应用程序中使用组件的运行时包(或根本没有包)。
如果你有一个组件图标,那么你也可以在注册单元中加载它(因为它只在设计时需要)。
Ray Konopka 写了一本关于组件编写的优秀书籍,它仍然非常有效:Developing Custom Delphi 3 Components
与许多优秀的 Delphi 书籍一样,它已绝版,但您可以在他的网站上订购 PDF 副本。
我不确定您的 CommentTitle 和 CommentText 属性是做什么用的,所以我将它们保存在下面的源代码中。
清单 1:实际组件
unit CustomSpeedButtonUnit;
interface
uses
SysUtils, Classes, Controls, Buttons;
const
DefaultCustomSpeedButtonCaption = 'Comments';
type
TCustomCustomSpeedButton = class(TSpeedButton)
strict private
FCommentText: string;
FCommentTitle: string;
strict protected
procedure SetCommentText(const Value: string); virtual;
procedure SetCommentTitle(const Value: string); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property CommentTitle: string read FCommentTitle write SetCommentTitle;
property CommentText: string read FCommentText write SetCommentText;
end;
TCustomSpeedButton = class(TCustomCustomSpeedButton)
published
// note you cannot use 'default' for string types; 'default' is only valid for ordinal ordinal, pointer or small set type
// [DCC Error] CustomSpeedButtonUnit.pas(29): E2146 Default values must be of ordinal, pointer or small set type
// property Caption default DefaultCustomSpeedButtonCaption;
property CommentTitle;
property CommentText;
end;
implementation
constructor TCustomCustomSpeedButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Caption := DefaultCustomSpeedButtonCaption;
ControlStyle := ControlStyle - [csSetCaption];
end;
destructor TCustomCustomSpeedButton.Destroy;
begin
inherited Destroy;
end;
procedure TCustomCustomSpeedButton.SetCommentText(const Value: string);
begin
FCommentText := Value;
end;
procedure TCustomCustomSpeedButton.SetCommentTitle(const Value: string);
begin
FCommentTitle := Value;
end;
end.
清单 2:组件注册
unit CustomSpeedButtonRegistrationUnit;
interface
procedure Register;
implementation
uses
CustomSpeedButtonUnit;
procedure Register;
begin
RegisterComponents('Standard', [TCustomSpeedButton]);
end;
end.