LiveBindings 覚え書き

Live BindingsのサンプルとかがDBとの連携ばっかりで、自作Classとの連携とかのがあんま無かったので調べた事の覚え書き

フォームにTEdit2個とTCheckBox1個。TButtonを2個配置する。後は、TPrototypeBindSourceを1個配置。
データを保持するクラスとしてTUserDataを定義。

  TUserData = class(TObject)
  private
    FInputBool: Boolean;
    FInputString1: string;
    FInputString2: string;
    procedure SetInputBool(const Value: Boolean);
    procedure SetInputString1(const Value: string);
    procedure SetInputString2(const Value: string);
  public
    property InputBool: Boolean read FInputBool write SetInputBool;
    property InputString1: string read FInputString1 write SetInputString1;
    property InputString2: string read FInputString2 write SetInputString2;
  end;

{ TUserData }

procedure TUserData.SetInputBool(const Value: Boolean);
begin
  FInputBool := Value;
end;

procedure TUserData.SetInputString1(const Value: string);
begin
  FInputString1 := Value;
end;

procedure TUserData.SetInputString2(const Value: string);
begin
  FInputString2 := Value;
end;


TPrototypeBindSource に上記クラスのプロパティと連携する為にstringフィールド2個とBoolフィールドを1個作る。

そして、LiveBingindデザイナを使って関連付けを行う。
TPrototypeBindSource とTUserDataを関連付ける為に、TPrototypeBindSource.OnCreateAdapterでAdapterを作成する。
オブジェクトと関連付ける場合は、TObjectBindSourceAdapterを使う。Listと関連付ける場合はTListBindSourceAdapterを使う。

procedure TForm1.PrototypeBindSource1CreateAdapter(Sender: TObject;
  var ABindSourceAdapter: TBindSourceAdapter);
begin
  ABindSourceAdapter := TObjectBindSourceAdapter<TUserData>.Create(Self,
    FData, False);
end;

こちらによると、TPrototypeBindSource.OnCreateAdapterがFormのOnCreateよりも先に呼ばれる為に、TObjectBindSourceAdapterとかTListBindSourceAdapterに渡すオブジェクトはOnCreateで作成するんじゃなくて、コンストラクタで作成する必要がある模様。

constructor TForm1.Create(AOwner: TComponent);
begin
  // TPrototypeBindSource.OnCreateAdapter が OnCreateForm よりも先に発生する
  // ので、OnCreateFormではなく、コンストラクタで初期化を行う
  FData := TUserData.Create;
  FData.InputBool := True;
  FData.InputString1 := '1';
  FData.InputString2 := '2';
  inherited;
end;

これで、TPrototypeBindSourceを介してFormのEditやCheckboxとTUserDataが関連付けられました。
TUserDataに変更を行った後や、EditやCheckBoxのOnChangeイベントでTPrototypeBindSource.Refreshを呼ぶ事でフォームの表示とTUserDataの同期が取られます。