如何在自定义delphi组件中实现stringlist属性?

Har*_*oux 7 delphi components tstringlist

我正在创建我的第一个自定义Delphi组件.它基本上是一个自定义的Tpanel,上面显示了标题和行文字.

我希望能够使用字符串列表添加多行文本.

测试组件时,添加行时无法在面板上显示文本行:NewLinesText.add('line1 text')

但是,当我在运行时创建并填充新的字符串列表然后将其分配给我的控件时,它确实有效:controlPanelitem.NewLinesText = MyNewStringlist

我希望能够添加如下行:NewLinesText.add('line1 text')

我在WinXP上使用Delphi 7专业版.见下面的代码.

任何帮助,将不胜感激!

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.
Run Code Online (Sandbox Code Playgroud)

And*_*and 9

你应该做

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

您可能还需要设置(在您创建自定义控件的构造函数中执行此操作时)的OnChange属性FLines.将其设置为组件的任何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;
Run Code Online (Sandbox Code Playgroud)