我想将一行换成灰色,另一行换成白色
我有以下代码,但在Windows 7中有垂直行列的空白。
如何为所有行着色?
procedure TForm2.Update_ListBoxCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
begin
if Item.Index mod 2=0
then
begin
Sender.Canvas.Font.Color:=clBlack;
Sender.Canvas.Brush.Color:=$F6F6F6;
end
else
begin
Sender.Canvas.Font.Color:=clBlack;
Sender.Canvas.Brush.Color:=clWhite;
end;
end;
答案 0 :(得分:9)
将OwnerDraw
设为true
并添加
procedure TForm1.ListView1DrawItem(Sender: TCustomListView; Item: TListItem;
Rect: TRect; State: TOwnerDrawState);
var
i: Integer;
x1, x2: integer;
r: TRect;
S: string;
const
DT_ALIGN: array[TAlignment] of integer = (DT_LEFT, DT_RIGHT, DT_CENTER);
begin
if Odd(Item.Index) then
begin
Sender.Canvas.Font.Color := clBlack;
Sender.Canvas.Brush.Color := $F6F6F6;
end
else
begin
Sender.Canvas.Font.Color := clBlack;
Sender.Canvas.Brush.Color := clWhite;
end;
Sender.Canvas.Brush.Style := bsSolid;
Sender.Canvas.FillRect(Rect);
x1 := 0;
x2 := 0;
r := Rect;
Sender.Canvas.Brush.Style := bsClear;
for i := 0 to ListView1.Columns.Count - 1 do
begin
inc(x2, ListView1.Columns[i].Width);
r.Left := x1;
r.Right := x2;
if i = 0 then
S := Item.Caption
else
S := Item.SubItems[i];
DrawText(Sender.Canvas.Handle,
S,
length(S),
r,
DT_SINGLELINE or DT_ALIGN[ListView1.Columns[i].Alignment] or
DT_VCENTER or DT_END_ELLIPSIS);
x1 := x2;
end;
end;
Screenshot http://privat.rejbrand.se/listviewrowcolors.png
在上面的示例中,第一列是左对齐的,另外两列是居中的。
如果您只有一列,即没有子项:
procedure TForm1.ListView1DrawItem(Sender: TCustomListView; Item: TListItem;
Rect: TRect; State: TOwnerDrawState);
var
r: TRect;
S: string;
const
DT_ALIGN: array[TAlignment] of integer = (DT_LEFT, DT_RIGHT, DT_CENTER);
begin
if odd(Item.Index) then
begin
Sender.Canvas.Font.Color:=clBlack;
Sender.Canvas.Brush.Color:=$F6F6F6;
end
else
begin
Sender.Canvas.Font.Color:=clBlack;
Sender.Canvas.Brush.Color:=clWhite;
end;
Sender.Canvas.Brush.Style := bsSolid;
Sender.Canvas.FillRect(Rect);
r := Rect;
Sender.Canvas.Brush.Style := bsClear;
S := Item.Caption;
DrawText(Sender.Canvas.Handle,
S,
length(S),
r,
DT_SINGLELINE or DT_ALIGN[ListView1.Columns[0].Alignment] or DT_VCENTER or DT_END_ELLIPSIS);
end;