How to change background color of FMX.TGrid row de

2019-07-02 02:59发布

问题:

I'd like to know how to change background color of whole row in Firemonkey TGrid/TColumn. Saw bunch of similar questions, but none of them helped me. I'm using Delphi XE4. TGrid may contain TCheckColumn and TStringColumn.

回答1:

TGrid row background style color is divided into two categories :

  • Focus color
  • Selection color

Focus color applies to the focused Cell. Selection color applies to the selected Row.

Changing focus color is a straight forward process:

procedure ChangeGridCellFocusColor(Grid: FMX.Grid.TGrid; NewColor: TAlphaColor);
var
  T: TFmxObject;
begin
  T := Grid.FindStyleResource('focus');
  if (T <> nil) and (T is TRectangle) then
    if TRectangle(T).Fill <> nil then
      TRectangle(T).Fill.Color := NewColor;
  Grid.Repaint;
end;

You apply it like this :

ChangeGridCellFocusColor(MyGrid1, TAlphaColors.Red);

Note that the Focus rectangle is semi-transparent so whatever color you assign it will mix with the Row Selection color.


It would be reasonable to assume that the Selection color can be changed in the same fashion but that is not the case.

When the Style is Applied the resource marked as selection is cloned, the original value discarded and the new value added to an internal TControlList. This is why the same principle cannot be applied.

To change the row selection color do the following:

Interface

type
  TcustomGridHelper = class helper for FMX.Grid.TCustomGrid
  public
    function getSelections: TControlList;
  end;

{...}

Implementation

function TcustomGridHelper.getSelections: TControlList;
begin
  Result := Self.fSelections;
end;


procedure ChangeGridRowSelectionColor(Grid: FMX.Grid.TGrid;
  NewColor: TAlphaColor);
var
  aList: TControlList;
  Control: TControl;
begin
  aList := Grid.getSelections;
  if (aList <> nil) then
    for Control in aList do
      TRectangle(Control).Fill.Color := NewColor;
  Grid.Repaint;
end;

You apply it like this :

ChangeGridRowSelectionColor(MyGrid1, TalphaColors.Green);