如何检查组件是否具有文本属性.当我读到Rtti将是一个很好的解决方案,但我之前没有使用它.任何帮助将不胜感激.
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;
Run Code Online (Sandbox Code Playgroud)
Vic*_*ria 12
例如,对于已发布的属性:
uses
System.TypInfo;
function HasTextProp(AControl: TControl): Boolean;
begin
Result := IsPublishedProp(AControl, 'Text');
end;
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
737 次 |
| 最近记录: |