2011-09-21 91 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能夠弄清楚如何使它成爲一種方式。 –