如何在自定义Delphi组件中实现字符串列表属性?

7
我正在创建我的第一个自定义 Delphi 组件,它基本上是一个带有标题和行文本的自定义 TPanel。
我希望能够使用 StringList 添加多行文本。但是,在测试组件时,当添加行时,文本行无法显示在面板上:NewLinesText.add('line1 text')。
然而,当我在运行时创建并填充一个新的 StringList,然后将其分配给我的控件时,它确实起作用:controlPanelitem.NewLinesText = MyNewStringlist。
我希望能够像这样添加行:NewLinesText.add('line1 text')。
我正在使用 WinXP 上的 Delphi 7 Professional。请参见下面的代码。
任何帮助都将不胜感激!
```unit ControlPanelItem;
interface uses SysUtils, Classes, Controls, ExtCtrls, Graphics, AdvPanel, StdCtrls, Windows,Forms,Dialogs;
type tControlPanelItem = class(TAdvPanel) private fLinesText : TStrings; procedure SetLinesText(const Value: TStrings); procedure SetText; protected public constructor Create(AOwner : TComponent); override; destructor Destroy; override; published property NewLinesText : TStrings read FLinesText write SetLinesText; end; procedure Register;
implementation procedure Register; begin RegisterComponents('Samples', [tControlPanelItem]); end;
constructor tControlPanelItem.Create(AOwner: TComponent); begin inherited; fLinesText := TStringList.Create; end;
destructor tControlPanelItem.Destroy; begin fLinesText.Free; inherited; end; procedure tControlPanelItem.SetLinesText(const Value: TStrings); begin fLinesText.Assign(value); SetText; end; procedure tControlPanelItem.SetText; var count : Integer; begin for count := 0 to fLinesText.Count - 1 do ShowMessage(fLinesText.strings[count]);
end;
end.```
1个回答

9

您应该做什么

procedure SetLines(Lines: TStrings);
begin
  FLinesText.Assign(Lines);
  // Repaint, update or whatever you need to do.
end;

您可能还需要设置FLinesOnChange属性(在创建自定义控件的构造函数中进行设置)。将其设置为组件中任何与TNofifyEvent兼容(私有或受保护,我猜)的过程。在这个过程中,您可以执行所需的重绘、更新等操作。

也就是说,执行以下操作:

constructor TControlPanelItem.Create(AOwner: TComponent);
begin
  inherited;
  FLinesText := TStringList.Create;
  TStringList(FLinesText).OnChange := LinesChanged;
end;

procedure TControlPanelItem.LinesChanged(Sender: TObject);
begin
  // Repaint, update or whatever you need to do.
end;

我已经在做这件事了。请查看过程tControlPanelItem.SetLinesText,该过程调用SetText。(过程SetText尚未完成。我只是使用showmessage来查看它是否有效) - Hardy Le Roux
好的,我没有看到那个。 (你知道,几分钟前代码不太好看!)但是我看不到任何 OnChange - Andreas Rejbrand
你好。谢谢您的快速回复。就我所知,FLinesText是一个字符串列表,并没有onchange属性? - Hardy Le Roux
@Delphiguy:是的,它有:http://docwiki.embarcadero.com/VCL/en/Classes.TStringList_Events。但由于变量声明为`TStrings`(**没有**此事件),因此您需要明确告诉编译器/IDE它是一个`TStringList`。请参阅我的更新。 - Andreas Rejbrand
这很令人困惑。FLinesText被声明为没有onchange属性的TStrings,然而,FLinesText被创建为具有onchange事件的TStringList。我应该进行类型转换吗? - Hardy Le Roux
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接