在 Firemonkey 中:从另一个组件获取样式对象

In Firemonkey: Get a style object from another component

我正在创建一个自定义组件,我想在该组件中使用 TGrid 中某些对象的某些颜色。我想尽可能多地使用样式颜色,以便我的应用程序具有一致的样式着色。

例如,我需要来自 TGridlinefill 对象

基本上:如何找到 linefill 对象 就像一个普通的按钮点击?

我可以这样解决:

procedure TForm46.Button2Click(Sender: TObject);
var
  sb: TFmxObject;
begin

  if not Assigned(BOGrid1.Scene.StyleBook) then
    sb := TStyleManager.ActiveStyleForScene(BOGrid1.Scene)
  else
    sb := BOGrid1.Scene.StyleBook.Style;

  var f := TBrush.Create(TBrushKind.Solid,TAlphaColorRec.Aqua);
  if Assigned(stylebook) then
  begin
    var st := sb.FindStyleResource('gridstyle', false);
    if Assigned(st) then
    begin
      var stobj := st.FindStyleResource('alternatingrowbackground');
      if (Assigned(stobj) and (stobj is TBrushObject)) then
      begin
        f.Assign((stobj as TBrushObject).Brush);
         button2.Text :=  intToStr(f.Color);
      end;
    end;
  end;


end;

其中 BOGrid1 是组件。

有关使用一些助手构建自己的组件时的更通用的答案:

interface

 TStylesHelper = class

    class function GetStyleObject(const StyleBook: TFmxObject; const Path: Array of string ): TFmxObject;
    class function GetStyleObjectBrush(const StyleBook: TFmxObject; const Path: Array of string): TBrush;

  end;


implementation


{ TStylesHelper }

class function TStylesHelper.GetStyleObject(const StyleBook: TFmxObject; const Path: array of string): TFmxObject;
begin

  if not Assigned(StyleBook) then
    Exit(nil);

  var fmxObject := StyleBook;
  for var styleName in Path do
  begin
    fmxObject := fmxObject.FindStyleResource(styleName);
    if fmxObject = nil then
      Exit(nil);
  end;

  result := fmxObject;

end;

class function TStylesHelper.GetStyleObjectBrush(const StyleBook: TFmxObject; const Path: array of string): TBrush;
begin
  result := nil;
  var bo := GetStyleObject(StyleBook, Path) as TBrushObject;
  if Assigned(bo) then
    result := bo.Brush;
end;

然后在组件的ApplyStyle protected方法中可以全部查看:

procedure TBOGrid.ApplyStyle;
var
  stylebook: TFmxObject;
begin
  inherited;

  if not Assigned(Scene) then
    Exit;

  if not Assigned(Scene.StyleBook) then
    stylebook := TStyleManager.ActiveStyleForScene(Scene)
  else
    stylebook := Scene.StyleBook.Style;

  if not Assigned(styleBook) then
    Exit();

  var lineFillBrush := TStylesHelper.GetStyleObjectBrush(stylebook, ['gridstyle','linefill']);
  if Assigned(lineFillBrush) then
    GridCellColor := lineFillBrush.Color
  else
    GridCellColor := DefaultGridCellColor;

   
end;