我现在有这个工作。我在设计器中完成了这一切,但已将其转换为主要代码以便在 SO 上更好地共享它。
创建一个 VCL 表单项目。在表格上,将这些中的每一个放在表格上:
TBindScope TBindingsList TButton TButton TEdit
将其中一个按钮重命名为 btnLoad,另一个重命名为 btnSave。
将此代码粘贴到您的表单单元上(假设它名为 Form1)。为按钮分配点击处理程序并运行它。单击 btnLoad 以使用 TPerson 对象数据填充编辑框,将编辑框中的文本编辑为新值,然后单击 btnSave 将其写回 TPerson 对象。
unit Form1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Rtti,
// LiveBinding units
System.Bindings.Helper, // Contains TBindings class
Data.Bind.EngExt,
Vcl.Bind.DBEngExt,
Data.Bind.Components,
System.Bindings.Outputs;
type
TPerson = class(TObject)
protected
fName: string;
fAge: integer;
procedure SetName(const Value: string);
public
property Name: string read fName write SetName;
property Age: integer read fAge write fAge;
end;
type
TForm1 = class(TForm)
btnLoad: TButton;
btnSave: TButton;
BindScope1: TBindScope;
BindingsList1: TBindingsList;
Edit1: TEdit;
procedure btnLoadClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
private
fInitialized: boolean;
fPerson: TPerson;
procedure Initialize;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.AfterConstruction;
begin
inherited;
Initialize;
end;
procedure TForm1.BeforeDestruction;
begin
fPerson.Free;
inherited;
end;
procedure TForm1.btnLoadClick(Sender: TObject);
begin
fPerson.Name := 'Doogie Howser';
fPerson.Age := 15;
BindScope1.DataObject := fPerson;
end;
procedure TForm1.btnSaveClick(Sender: TObject);
begin
TBindings.Notify(Edit1, '');
// Could also do this:
//BindingsList1.Notify(Edit1, '');
end;
procedure TForm1.Initialize;
var
expression: TBindExpression;
begin
// Create a binding expression.
expression := TBindExpression.Create(self);
expression.ControlComponent := Edit1;
expression.ControlExpression := 'Text'; // The Text property of Edit1 ...
expression.SourceComponent := BindScope1;
expression.SourceExpression := 'Name'; // ... is bound to the Name property of fPerson
expression.Direction := TExpressionDirection.dirBidirectional;
// Add the expression to the bindings list.
expression.BindingsList := BindingsList1;
// Create a Person object.
fPerson := TPerson.Create;
end;
{ TPerson }
procedure TPerson.SetName(const Value: string);
begin
fName := Value;
ShowMessage('Name changed to "'+ Value +'"');
end;
end.