unit ViewFormMain;
interface
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls;
type
TViewModel =
class
private
FValue : Boolean;
FOnUpdate : TNotifyEvent;
procedure SetValue(
const Value : Boolean );
protected
procedure DoUpdate;
public
property OnUpdate : TNotifyEvent
read FOnUpdate
write FOnUpdate;
property Value : Boolean
read FValue
write SetValue;
end;
TMainFormView =
class( TForm )
Edit1 : TEdit;
// OI: OnChange => ControlChange
Edit2 : TEdit;
// OI: OnChange => ControlChange
Edit3 : TEdit;
// OI: OnChange => ControlChange
CheckBox1 : TCheckBox;
// OI: OnClick => ControlChange
procedure ControlChange( Sender : TObject );
procedure FormShow( Sender : TObject );
private
FModelLoading : Boolean;
FViewModel : TViewModel;
protected
procedure DoLoadFromModel;
virtual;
procedure DoSaveToModel;
virtual;
procedure ViewModelUpdate( Sender : TObject );
protected
procedure LoadFromModel;
procedure SaveToModel;
procedure SyncWithModel;
public
procedure AfterConstruction;
override;
procedure BeforeDestruction;
override;
property ViewModel : TViewModel
read FViewModel;
end;
var
MainFormView : TMainFormView;
implementation
{$R *.dfm}
{ TForm1 }
procedure TMainFormView.AfterConstruction;
begin
inherited;
FViewModel := TViewModel.Create;
FViewModel.OnUpdate := ViewModelUpdate;
end;
procedure TMainFormView.BeforeDestruction;
begin
inherited;
FViewModel.Free;
end;
procedure TMainFormView.ControlChange( Sender : TObject );
begin
SyncWithModel;
end;
procedure TMainFormView.DoLoadFromModel;
begin
// Binding Model => View
CheckBox1.Checked := ViewModel.Value;
Edit1.Enabled :=
not ViewModel.Value;
Edit2.Enabled :=
not ViewModel.Value;
Edit3.Enabled :=
not ViewModel.Value;
end;
procedure TMainFormView.DoSaveToModel;
begin
// Binding View => Model
ViewModel.Value := CheckBox1.Checked;
end;
procedure TMainFormView.FormShow( Sender : TObject );
begin
LoadFromModel;
end;
procedure TMainFormView.LoadFromModel;
begin
if FModelLoading
then
Exit;
FModelLoading := True;
try
DoLoadFromModel;
finally
FModelLoading := False;
end;
end;
procedure TMainFormView.SaveToModel;
begin
if FModelLoading
then
Exit;
DoSaveToModel;
end;
procedure TMainFormView.SyncWithModel;
begin
SaveToModel;
LoadFromModel;
end;
procedure TMainFormView.ViewModelUpdate( Sender : TObject );
begin
LoadFromModel;
end;
{ TViewModel }
procedure TViewModel.DoUpdate;
begin
if Assigned( OnUpdate )
then
OnUpdate( Self );
end;
procedure TViewModel.SetValue(
const Value : Boolean );
begin
if Value = FValue
then
Exit;
FValue := Value;
DoUpdate;
end;
end.