TStringGrid 提供 OnDrawCell 事件可自訂每儲存格外觀,常見需求包括整體背景色與隔列換色(斑馬紋)。
直接設定 Color 屬性即可,或在 OnDrawCell 中統一填滿。
procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
begin
with StringGrid1 do
begin
// 標題列(第 0 列)不處理
if ARow = 0 then Exit;
// 偶數列套用淺藍背景
if ARow mod 2 = 0 then
begin
Canvas.Brush.Color := clInfoBk; // 或自訂色彩 $E0F0FF
Canvas.Font.Color := clNavy;
end
else
begin
Canvas.Brush.Color := clWhite;
Canvas.Font.Color := clBlack;
end;
// 繪製背景與文字
Canvas.FillRect(Rect);
Canvas.TextOut(Rect.Left + 2, Rect.Top + 2, Cells[ACol, ARow]);
end;
end;
Canvas.FillRect 與 TextOut,否則只會改變筆刷而不實際繪製。DefaultDrawing = True(預設),先填滿背景再呼叫 DefaultDrawCell 可保留焦點框與選取效果。State 含 gdSelected、gdFocused 等,可據此調整選取列顏色。