2011-09-21 86 views
9

我有以下示例代码集,我如何使用LiveBindings将Data列表元素绑定到TStringGrid。我需要双向更新,这样当网格中的列发生更改时,它可以更新底层的TPersonLiveBindings - 绑定到TStringGrid的TList <TMyObject>

我见过如何使用基于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. 
+0

的答案是有帮助这个问题? [需要双向-livebindings-之间-A-控制和 - 一个对象(http://stackoverflow.com/questions/7478785/need-bidirectional-livebindings-between-a-control-and-an-object) –

+0

不...菲尔(谁问/回答了这个问题),我是同事试图想出这一切。但还没有弄清楚表达式需要使网格工作。 –

+0

好的,我猜FM框架目前缺少一些文档。作为一个旁注,在代码中或者在设计器中隐藏这个链接的首选方式是什么?我个人很讨厌隐藏代码的逻辑。 –

回答

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; 
+0

+1能够弄清楚如何使它成为一种方式。 –