Thema: String2Class

Einzelnen Beitrag anzeigen

Benutzerbild von TRomano
TRomano

Registriert seit: 24. Nov 2004
Ort: Düsseldorf
190 Beiträge
 
Delphi 11 Alexandria
 
#12

AW: String2Class

  Alt 12. Mär 2015, 15:26
Da es ja letztlich um das Setzen einer Property geht, geht auch das:

Delphi-Quellcode:
type TDictionaryControls = TDictionary<TControl,string>; // im String wird der Property-Name gespeichert
     
     TForm1 = class(TForm)
...
      procedure SetControlProperty(pControl : TControl; const PropValue : string);


var dictControls : TDictionaryControls;

...

procedure TForm1.FormCreate(Sender: TObject);
begin
  dictControls : TDictionaryControls.Create(3);
  dictControls.Add(Button1,'Caption');
  dictControls.Add(Label1 ,'Caption');
  dictControls.Add(Edit1 ,'Text');
end;

procedure TForm1.SetControlProperty(pControl : TControl; const PropValue : string);
var aContext : TRTTIContext;
    aProperty : TRTTIProperty;
    aValue : TValue;
    sPropName : string;
begin
  if (pControl = nil) or (not dictControls.TryGetValue(pControl,sPropName) then Exit;
 
  // mit Prüfung auf Property-Name
  aProperty := aContext.GetType(pControl.ClassInfo).GetProperty(sPropName);
  if Assigned(aProperty) then begin
     aValue := TValue.From(PropValue);
     aProperty.SetValue(pControl,aValue);
  end;
 
  // hier ohne Prüfung und mit "alter" RTTI
  System.TypInfo.SetStrProp(pControl,sPropName,PropValue);
end;
Aufruf erfolgt dann mit: SetControlProperty(Button1,'Exit');

Ist nur so hingetippert, also ungeprüft ...

Gruß Thomas
Thomas Forget
  Mit Zitat antworten Zitat