2

我正在尝试使用 OnCustomDrawItem 事件自定义 ListView 项目的背景颜色和字体颜色。但是 subitem 的边框颜色始终是 ListView 的背景颜色。有谁知道如何解决这一问题?这是我正在使用的代码:

procedure TForm1.ListView1CustomDrawItem(Sender: TCustomListView;
  Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
var
  lst: TListView;
  i: integer;
  f1, f2, c1, c2: TColor;
begin
  if (TListView(Sender).ViewStyle = vsIcon) then
    Exit;
  lst := Sender as TListView;
  lst.Canvas.Brush.Style := bsSolid;
  i := lst.Items.Count;
  if (i mod 2) <> 0 then
  begin
    c1 := clWhite;
    c2 := $00F8F8F8;
    f1 := clBlue;
    f2 := clBlack;
  end else
  begin
    c1 := $00F8F8F8;
    c2 := clWhite;
    f1 := clBlack;
    f2 := clBlue;
  end;
  // Painting...
  if (Item.Index mod 2) = 0 then
  begin
    lst.Canvas.Brush.Color := c2;
    lst.Canvas.Font.Color := f2;
  end else
  begin
    lst.Canvas.Brush.Color := c1;
    lst.Canvas.Font.Color := f1;
  end;
end;

编辑:

SubItems 列之间存在 GAP。这个 GAP 是 ListView 的背景颜色。

我使用 Delphi XE2 和操作系统:Windows 7 bit bit。

4

1 回答 1

1

尝试 OnAdvancedCustomDrawItem 而不是您的 CustomDrawItem 过程

procedure TForm1.ListView1AdvancedCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage;
var DefaultDraw: Boolean);
var
  lst: TListView;
  i: integer;
  f1, f2, c1, c2: TColor;
  r: TRect;
begin
  if Stage = cdPostPaint then
  begin
    lst := Sender as TListView;
    lst.Canvas.Brush.Style := bsSolid;
    i := lst.Items.Count;
    if not Odd(i) then
    begin
      c1 := clWhite;
      c2 := $00F8F8F8;
      f1 := clBlue;
      f2 := clBlack;
    end else
    begin
      c1 := $00F8F8F8;
      c2 := clWhite;
      f1 := clBlack;
      f2 := clBlue;
    end;
    // Painting...
    if Odd(Item.Index) then
    begin
      lst.Canvas.Brush.Color := c2;
      lst.Canvas.Pen.Color := c2;
      lst.Canvas.Font.Color := f2;
    end else
    begin
      lst.Canvas.Brush.Color := c1;
      lst.Canvas.Pen.Color := c1;
      lst.Canvas.Font.Color := f1;
    end;

    r:=Item.DisplayRect(drBounds);

    if cdsSelected in State then
    begin
      lst.Canvas.Brush.Color:=clHighlight;
      lst.Canvas.Pen.Color:=clHighlight;
      lst.Canvas.Font.Color:=clBlack;
    end;

    lst.Canvas.Rectangle(r);

    if cdsSelected in State then
      lst.Canvas.DrawFocusRect(r);

    lst.Canvas.TextOut(r.Left, r.Top + (r.Bottom - r.top - lst.Canvas.TextHeight(Item.Caption)) div 2, Item.Caption);
    for i := 0 to Item.SubItems.Count - 1 do
    begin
      r.Left:=r.Left + lst.Columns[i].Width;
      lst.Canvas.TextOut(r.Left, r.Top + (r.Bottom - r.top - lst.Canvas.TextHeight(Item.Caption)) div 2, Item.SubItems[i]);
    end;
  end;
end;

希望这可以帮助。

于 2012-09-27T14:50:57.753 回答