您可以通過使用OnDrawCell
事件(執行而不是將DefaultDraw
設置爲False)來執行此操作。下面是與常規TStringGrid
一個例子:
上面確切的代碼的
// Sample to populate the cells with the days of the week
procedure TForm1.FormShow(Sender: TObject);
var
r, c: Integer;
begin
StringGrid1.ColCount := 8; // Ignore fixed column and row for this example
StringGrid1.RowCount := 8;
for c := 1 to StringGrid1.ColCount - 1 do
for r := 1 to StringGrid1.RowCount - 1 do
StringGrid1.Cells[c, r] := FormatSettings.ShortDayNames[c];
end;
// Assign this to the StringGrid's OnDrawCell using the Object Inspector
// Events tab.
procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
CellText: string;
begin
if (ARow > 0) and (ACol > 0) then
begin
CellText := StringGrid1.Cells[ACol, ARow];
if Pos('Sun', CellText) > 0 then
begin
StringGrid1.Canvas.Brush.Color := clRed;
StringGrid1.Canvas.FillRect(Rect);
end
else
StringGrid1.Canvas.Brush.Color := clWindow;
end;
// The '+ 4' is from the VCL; it's hard-coded when themes are enabled.
// You should probably check the grid's DrawingStyle to see if it's
// gdsThemed, and adjust as needed. I leave that as an exercise for you.
StringGrid1.Canvas.TextOut(Rect.Left + 4, Rect.Top + 4, CellText);
end;
輸出示例:
下面是輸出只是正是你想要的第二個例子(除了我沒有轉換太陽蓋):
procedure TForm1.FormShow(Sender: TObject);
var
r, c: Integer;
begin
StringGrid1.DefaultColWidth := 100;
StringGrid1.ColCount := 8;
StringGrid1.RowCount := 8;
for c := 1 to StringGrid1.ColCount - 1 do
for r := 1 to StringGrid1.RowCount - 1 do
StringGrid1.Cells[c, r] := FormatDateTime('mm/dd/yyyy ddd',
Date() + c + r - 1);
end;
procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
CellText: string;
begin
if (ARow > 0) and (ACol > 0) then
begin
CellText := StringGrid1.Cells[ACol, ARow];
if Pos('Sun', CellText) > 0 then
StringGrid1.Canvas.Brush.Color := clRed
else
StringGrid1.Canvas.Brush.Color := clWindow;
StringGrid1.Canvas.FillRect(Rect);
end;
StringGrid1.Canvas.TextOut(Rect.Left + 4, Rect.Top + 4, CellText);
end;
這裏的捕獲到第二樣品不一致:
它不適用於我的情況。我也有這個日期。也就是這個顏色只有活動的單元格。如果在列名中存在單詞SUN,我想爲整列(包括固定單元格)着色。 – user763539
你的這段代碼也清除了我的細胞內容,因此我無法看到任何東西... – user763539
嗯,不,它不。 :)我會添加一個屏幕截圖。它還會爲任何包含文本「Sun」的單元格(通過使用上面代碼中的「Pos」找到)而不僅僅是活動單元格着色。您必須調整代碼以符合您的確切需求;我發佈的是如何做的例子,但這只是一個起點。 :) –