Home > Enterprise >  In Firemonkey: Get a style object from another component
In Firemonkey: Get a style object from another component

Time:12-04

I'm creating a custom component and in that component i want to use certain colors from certain objects in the TGrid. I want to use style colors as much as I can so that my application will have consistent style coloring.

I need for example the linefill object from the TGrid.

Basically: how do I find that linefill object from like a plain button click?

CodePudding user response:

I could solve it like:

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;

Where BOGrid1 is the component.

For a more generic answer for when you build your own component with a few helpers:

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;

Then in the ApplyStyle protected method of the component you can look it all up:

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;
  • Related