LiveBindings - 将 TList<TMyObject> 绑定到 TStringGrid

10
我有以下示例代码集合,如何使用LiveBindings将Data列表元素绑定到TStringGrid。我需要双向更新,以便在网格中更改列时可以更新基础的TPerson。我看到了如何使用基于TDataset的绑定来进行此操作的示例,但我需要在没有TDataset的情况下完成此操作。
unit Unit15;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, System.Generics.Collections;

type
  TPerson = class(TObject)
  private
    FLastName: String;
    FFirstName: string;
  published
    property firstname : string read FFirstName write FFirstName;
    property Lastname : String read FLastName write FLastName;
  end;

  TForm15 = class(TForm)
    StringGrid1: TStringGrid;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    Data : TList<TPerson>;
  end;


var
  Form15: TForm15;



implementation

{$R *.dfm}

procedure TForm15.FormCreate(Sender: TObject);
var
 P : TPerson;
begin
  Data := TList<TPerson>.Create;
  P := TPerson.Create;
  P.firstname := 'John';
  P.Lastname := 'Doe';
  Data.Add(P);
  P := TPerson.Create;
  P.firstname := 'Jane';
  P.Lastname := 'Doe';
  Data.Add(P);
  // What can I add here or in the designer to link this to the TStringGrid.
end;

end.

这个问题的答案有帮助吗?需要在控件和对象之间进行双向实时绑定 - LU RD
好的,我猜FM框架目前缺乏一些文档。顺便说一下,将来做这种链接的首选方式是在代码中还是隐藏在设计师中?个人而言,我不喜欢把逻辑隐藏在代码中。 - LU RD
LiveBindings 可以与 VCL 一起使用,不仅限于 FM。最好的方式将在我看到实现方法后才能确定。但是个人而言,我更喜欢通过代码来展示事物。 - Robert Love
1
我已经尝试了一个小时,但是无法弄清楚这个问题。看起来应该很容易解决,但不知道为什么却不行。希望有人能提出解决方案! - Birger
1
@Jim,我们没有想出来。我们完成了绑定系统的编写,这更容易些。 - Robert Love
显示剩余4条评论
1个回答

8

解决方案的一部分:从TList到TStringGrid是:

procedure TForm15.FormCreate(Sender: TObject); 
var 
 P : TPerson; 
 bgl: TBindGridList;
 bs: TBindScope;
 colexpr: TColumnFormatExpressionItem;
 cellexpr: TExpressionItem;
begin 
  Data := TList<TPerson>.Create; 
  P := TPerson.Create; 
  P.firstname := 'John'; 
  P.Lastname := 'Doe'; 
  Data.Add(P); 
  P := TPerson.Create; 
  P.firstname := 'Jane'; 
  P.Lastname := 'Doe'; 
  Data.Add(P); 
  // What can I add here or in the designer to link this to the TStringGrid. 

  while StringGrid1.ColumnCount<2 do
    StringGrid1.AddObject(TStringColumn.Create(self));

  bs := TBindScope.Create(self);

  bgl := TBindGridList.Create(self);
  bgl.ControlComponent := StringGrid1;
  bgl.SourceComponent := bs;

  colexpr := bgl.ColumnExpressions.AddExpression;
  cellexpr := colexpr.FormatCellExpressions.AddExpression;
  cellexpr.ControlExpression := 'cells[0]';
  cellexpr.SourceExpression := 'current.firstname';

  colexpr := bgl.ColumnExpressions.AddExpression;
  cellexpr := colexpr.FormatCellExpressions.AddExpression;
  cellexpr.ControlExpression := 'cells[1]';
  cellexpr.SourceExpression := 'current.lastname';

  bs.DataObject := Data;
end; 

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