BindingList的主要特点在于,它可以在加入新的元素或者元素发生修改的时候触发相应的事件,而在基本集合类中是不具有这些功能的,而且由于在基本集合中Add方法不是Virtual方法,要想让它触发时间还真不是很方便。不过BindingList可以很好的满足你的功能。
最近做项目中突然发现还有个BindingList可以使用。查了不少信息。得出底下几点结论:
- 压根不是同一样东西,从命名空间中就能发现,一个是Component下的东西。主要特点在于Component的相关。另一个是Collection命名空间下的产物。主要用于集合相关。
- BindingList比List多的功能问为但他是GridView的数据源时,他有Allow.... Sort...等方法。从名字中可以看出对于该数据的一些约束。List比BindingList多的方法比如,AddRange方法,我之前项目中使用BindingList时需要将2个BindingList合并,却找不到方法。当然他可能有其他的方法而我不知道而已。
- 最后,BindingList和List并无任何关系不存在继承关系。个人建议,处理逻辑时用List,但作为数据源绑定是用BindingList.
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.Bind.EngExt, Vcl.Bind.DBEngExt,
Vcl.StdCtrls, Data.Bind.Components, Vcl.Grids;
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)
BindScope1: TBindScope;
BindingsList1: TBindingsList;
Edit1: TEdit;
btnLoad: TButton;
btnSave: TButton;
procedure btnLoadClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
private
fInitialized: boolean;
fPerson: TPerson;
procedure Initialize;
{ Private declarations }
public
{ Public declarations }
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
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.