How can I check if the component has a text property. As I read Rtti will be a good soulution but I did not worked with it before. Any help would be greatly appreciated.
function HasTextProp(aControl: TControl): Boolean;
begin
Result := False;
if (aComponent is ?) then
Exit(True);
end;
var
ObjList: TObjectList<TControl>;
ObjIdx: Integer;
begin
ObjList := TObjectList<TControl>.Create,
ObjList.Add(comp1); {is TcxButton}
ObjList.Add(comp2); {is Tedit}
ObjList.Add(comp3); {is TDateTimeEdit}
for ObjIdx := 0 to lObjList.Count -1 do
begin
if HasTextProp(lObjList.Items[ObjIdx]) then
do something...
end;
end;
For example for published properties:
uses
System.TypInfo;
function HasTextProp(AControl: TControl): Boolean;
begin
Result := IsPublishedProp(AControl, 'Text');
end;
Victoria showed you how to accomplish your goal using old-style RTTI, which works only with published properties and nothing else. In Delphi 2010 and later, there is a new-style RTTI that works with almost everything (private/protected/public/published, properties, data members, etc), and can also accomplish your goal, eg:
uses
..., System.TypInfo, System.Rtti;
function HasTextProp(aControl: TControl): Boolean;
var
Ctx: TRttiContext;
Prop: TRttiProperty;
begin
Prop := Ctx.GetType(aControl.ClassType).GetProperty('Text');
Result := (Prop <> nil) and (Prop.Visibility in [mvPublic, mvPublished]);
end;
TRttiProperty has GetValue() and SetValue() methods, eg:
var
Ctrl: TControl
Ctx: TRttiContext;
Prop: TRttiProperty;
begin
...
Ctrl := lObjList.Items[ObjIdx];
Prop := Ctx.GetType(Ctrl.ClassType).GetProperty('Text');
if (Prop <> nil) and (Prop.Visibility in [mvPublic, mvPublished]) then
begin
if Prop.GetValue(Ctrl).IsEmpty then
Prop.SetValue(Ctrl, 'Not Empty Anymore!');
end;
...
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With