这类似于您的other RTTI issue,您正在通过RTTI 访问控件的TextSettings.Font 属性。这同样适用于任何嵌套属性,例如 Stroke.Color 等。
对于每个嵌套的子属性,您必须获取包含对象,根据需要重复,直到您到达所需的子对象,然后您可以获取/设置根据需要设置其属性值。
因此,在这种情况下,您必须使用GetObjectProp() 来获取Stroke 属性对象,然后您可以使用SetPropValue() 来设置该对象的属性。例如:
uses
..., TypInfo;
var
Componente_cc: TControl;
procedure TfrmPrincipal.AlteraPropriedades;
var
Stroke: TObject;
begin
if IsPublishedProp(Componente_cc, 'Stroke') then
begin
Stroke := GetObjectProp(Componente_cc, 'Stroke');
if Stroke <> nil then
SetPropValue(Stroke, 'Color', ...);
end;
end;
或者,为了避免命名属性的双重 RTTI 查找:
uses
..., TypInfo;
var
Componente_cc: TControl;
procedure TfrmPrincipal.AlteraPropriedades;
var
PropInfo: PPropInfo;
Stroke: TObject;
begin
PropInfo := GetPropInfo(Componente_cc, 'Stroke', [tkClass]);
if PropInfo <> nil then
begin
Stroke := GetObjectProp(Componente_cc, PropInfo);
if Stroke <> nil then
SetPropValue(Stroke, 'Color', ...);
end;
end;
请注意,在 Delphi 2010 中引入了更强大的Enhanced RTTI(此 RTTI 不仅限于发布的属性,就像旧式 RTTI 一样),例如:
uses
..., System.Rtti;
var
Componente_cc: TControl;
procedure TfrmPrincipal.AlteraPropriedades;
var
Ctx: TRttiContext;
Prop: TRttiProperty;
Stroke: TObject;
begin
Ctx := TRttiContext.Create;
Prop := Ctx.GetType(Componente_cc.ClassType).GetProperty('Stroke');
if (Prop <> nil) and (Prop.PropertyType.TypeKind = tkClass) {and (Prop.Visibility = mvPublished)} then
begin
Stroke := Prop.GetValue(Componente_cc).AsObject;
if Stroke <> nil then
begin
Prop := Ctx.GetType(Stroke.ClassType).GetProperty('Color');
if (Prop <> nil) {and (Prop.Visibility = mvPublished)} then
Prop.SetValue(Stroke, ...);
end;
end;
end;
但是,一旦您可以访问更高级别的对象,最好直接访问子属性,例如:
uses
..., TypInfo;
var
Componente_cc: TControl;
procedure TfrmPrincipal.AlteraPropriedades;
var
PropInfo: PPropInfo;
Stroke: TStrokeBrush;
begin
PropInfo := GetPropInfo(Componente_cc, 'Stroke', [tkClass]);
if PropInfo <> nil then
begin
Stroke := GetObjectProp(Componente_cc, PropInfo, TStrokeBrush) as TStrokeBrush;
if Stroke <> nil then
Stroke.Color := ...; // <-- no RTTI needed!
end;
end;
或者:
uses
..., System.Rtti;
var
Componente_cc: TControl;
procedure TfrmPrincipal.AlteraPropriedades;
var
Ctx: TRttiContext;
Prop: TRttiProperty;
Stroke: TStrokeBrush;
begin
Ctx := TRttiContext.Create;
Prop := Ctx.GetType(Componente_cc.ClassType).GetProperty('Stroke');
if (Prop <> nil) and (Prop.PropertyType.TypeKind = tkClass) {and (Prop.Visibility = mvPublished)} then
begin
Stroke := Prop.GetValue(Componente_cc).AsObject as TStrokeBrush;
if Stroke <> nil then
Stroke.Color := ...; // <-- no RTTI needed!
end;
end;