Binding to DataContext doesn't work

Issue #39 new
Former user created an issue

I'm trying to bind a "View" to its Datacontext like so :

interface

type

TMyDataContext = class(TObject, INotifyPropertyChanged)
private
  FValue : string;
  FOnPropertyChanged : Event<TPropertyChangedEvent>;
  procedure SetValue(const aValue : string);
  function GetPropertyChanged : IEvent<TPropertyChangedEvent>;
public
  property Value : string read FValue write SetValue;
  property OnPropertyChanged : IEvent<TPropertyChangedEvent> read GetPropertyChanged;
end;


TMyView = class(TForm)
Edit1 : TEdit;
BindingGroup1 : TBindingGroup;
public
constructor Create(aOwner : TComponent);
end;

implementation

function TMyDataContext.GetPropertyChanged : IEvent<TPropertyChangedEvent>;
begin
  Result := FOnPropertyChanged;
end;

procedure TMyDataContext.SetValue(const aValue : string);
begin
if aValue <> FValue then
begin
FValue := aValue;
OnPropertyChanged.Invoke(Self, TPropertyChangedArgs.Create('Value'));
OnPropertyChanged.Invoke(Self, TPropertyChangedArgsEx.Create('Value', utPropertyChanged)); // also tried with this
end;
end;

constructor TMyView.Create(aOwner : TComponent);
var
aDataContext : TMyDataContext;
begin
inherited Create(aOwner);
aDataContext := TMyDataContext.Create;
DataContext := aDataContext ;

BindingGroup1.AddBinding(Self, 'DataContext.Value', Edit1, 'Text');

aDataContext.Value := 'MyNewValue' // Does not change the Edit1.Text value

end;


end.

Comments (1)

  1. Stefan Glienke repo owner

    You need to notify the TMyView instance that its property DataContext has been changed. Only then it will update. If your notification starts somewhere in the middle of the expression (in your case only the ".Value" part gets notified) it will not reach the binding.

  2. Log in to comment