I use the example of the cell in a TGrid column as an example. There is no color property in the components option. THe color is only accessible by code. The code must go
The FMX
framework offers a couple of means to change the appearance of the background of a TGrid
. Two means, alternating row colors and color per cell are presented in the following.
Alternating row colors, optionally using styles
This exists as a presetable boolean item in the TGrid.Options
property named AlternateRowBackground
. The default color is a light gray color ($FFEEEEEE). To change this color you can add a TStyleBook
or right click the grid and select Edit Custom Style ...
or Edit Default Style ...
and then change the Color
property of gridstyle - alternatingrowbackground
. Here an example where the color is changed to Bisque
:
Code in the OnDrawColumnCell
event
This even is called for each cell of the grid and offers full control of painting the cell background. The header of the event handler looks like this:
procedure TForm11.Grid1DrawColumnCell(Sender: TObject; const Canvas: TCanvas;
const Column: TColumn; const Bounds: TRectF; const Row: Integer;
const Value: TValue; const State: TGridDrawStates);
For painting we will need a TBrush
, so we declare one as a local variable:
var
bgBrush: TBrush;
We are now ready to apply some scenarios of special background drawing. First is how to let the default drawing take place for certain cell states.
if (TGridDrawState.Selected in State) or
(TGridDrawState.Focused in State) then
begin
Grid1.DefaultDrawColumnCell(Canvas, Column, Bounds, Row, Value, State);
Exit;
end;
For the following we will need the TBrush
, so we create it and manage its lifetime (on Windows platform):
bgBrush:= TBrush.Create(TBrushKind.Solid, TAlphaColors.White); // default white color
try
//
// following code snippets go in here
//
finally
bgBrush.Free;
end;
Next, an example of painting alternating row backgrounds without using styles
if Odd(Row) then
bgBrush.Color := TAlphaColors.MoneyGreen+$202020; // a very light green color
Canvas.FillRect(Bounds, 0, 0, [], 1, bgBrush);
Then an example of background color for given columns
case Column.Index of
0: bgBrush.Color := TAlphaColors.lightBlue;
1: bgBrush.Color := TAlphaColors.MoneyGreen;
end;
Canvas.FillRect(Bounds, 0, 0, [], 1, bgBrush);
And finally an example of background color determined by value of data
if Column.Index = 1 then
if Value.AsOrdinal < 0 then // negative
bgBrush.Color := TAlphaColors.Lightpink
else
bgBrush.Color := TAlphaColors.MoneyGreen;
Canvas.FillRect(Bounds, 0, 0, [], 1, bgBrush);
And a sample image:
The texts are colored as in this answer