gpt4 book ai didi

delphi - LiveBindings - TList 绑定(bind)到 TStringGrid

转载 作者:行者123 更新时间:2023-12-03 14:42:10 24 4
gpt4 key购买 nike

我有以下示例代码集,如何使用 LiveBindings 将 Data 列表元素绑定(bind)到 TStringGrid。我需要双向更新,以便当网格中的列发生更改时,它可以更新底层 TPerson

我已经看到了如何使用基于 TDataset 的绑定(bind)来执行此操作的示例,但我需要在没有 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.

最佳答案

部分解决方案:从 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;

关于delphi - LiveBindings - TList<TMyObject> 绑定(bind)到 TStringGrid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7507838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com