Delphi XE2 之 FireMonkey 入门(26) - 数据绑定: TBindingsList: TBindExprItems


如果要给一对 "源控件" 和 "目标控件" 写多个表达式, 使用 TBindExpression 就不如 TBindExprItems 了.

TBindExprItems 中的表达式又分两组: FormatExpressions、ClearExpressions, 后者是在断开绑定时的表达式.

示例设想:
1、TrackBar1 为源, 把其 Value 值绑定给 Edit1.Text 和 Edit1.Width 和 Label1.Text;
2、断开绑定时, 在 Edit1 中显示 "已断开绑定".

先在窗体上添加: TrackBar1、Edit1、Label1、BindingsList1、CheckBox1, 然后激活 TrackBar1、ChengkBox1 和窗体的默认事件:

unit Unit1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, Data.Bind.EngExt,
  Fmx.Bind.DBEngExt, Data.Bind.Components, FMX.Edit;

type
  TForm1 = class(TForm)
    TrackBar1: TTrackBar;
    Edit1: TEdit;
    Label1: TLabel;
    BindingsList1: TBindingsList;
    CheckBox1: TCheckBox;
    procedure FormCreate(Sender: TObject);
    procedure TrackBar1Change(Sender: TObject);
    procedure CheckBox1Change(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

var
  bindExprItems: TBindExprItems;

procedure TForm1.FormCreate(Sender: TObject);
begin
  bindExprItems := TBindExprItems.Create(BindingsList1);
  with bindExprItems do
  begin
    ControlComponent := Edit1;    //目标控件
    SourceComponent := TrackBar1; //源控件
    {把 TrackBar1.Value 绑定到 Edit1.Text}
    with FormatExpressions.AddExpression do
    begin
      ControlExpression := 'Text';
      SourceExpression := 'Value';
    end;
    {把 TrackBar1.Value 绑定到 Edit1.Width}
    with FormatExpressions.AddExpression do
    begin
      ControlExpression := 'Width';
      SourceExpression := 'Value';
    end;
    {把 TrackBar1.Value 绑定到 Label1.Text}
    with FormatExpressions.AddExpression do
    begin
      ControlExpression := 'Owner.Label1.Text'; //Owner
      SourceExpression := 'Value';
    end;
    {当要断开绑定时...}
    with ClearExpressions.AddExpression do
    begin
      ControlExpression := 'Self.Text';  //这里的 Self 是指目标控件本身, 可省略
      SourceExpression := '"已断开绑定"';
    end;
    Active := True;
  end;
  CheckBox1.IsChecked := True;
  TrackBar1.Max := ClientWidth;
end;

procedure TForm1.TrackBar1Change(Sender: TObject);
begin
  BindingsList1.Notify(Sender, 'Value');
end;

procedure TForm1.CheckBox1Change(Sender: TObject);
begin
  bindExprItems.Active := TCheckBox(Sender).IsChecked;
end;

end.

你可能感兴趣的:(Delphi)