2006. május 7., vasárnap

How to highlight alternate rows in a TListView


Problem/Question/Abstract:

How to highlight alternate rows in a TListView

Answer:

The following will draw all alternate lines with yellow text on blue background. It uses the OnAdvancedCustomDraw events of the listview. As a bonus you get full highlighting of selected lines.

procedure CheckPaintstage(Stage: TCustomDrawStage; itemIndex: Integer; canvas:
  TCanvas);
begin
  if Stage in [cdPrePaint, cdPreErase] then
  begin
    if Odd(itemIndex) then
    begin
      Canvas.Brush.Color := clBlue;
      if Stage = cdPrepaint then
        Canvas.Font.color := clYellow;
    end
  end;
end;

procedure TForm1.ListView1AdvancedCustomDrawItem(Sender: TCustomListView;
  Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage;
  var DefaultDraw: Boolean);
begin
  if not (cdsSelected in State) then
    CheckPaintstage(Stage, item.Index, sender.canvas)
  else
    Sender.Canvas.Brush.Color := clHighlight;
end;

procedure TForm1.ListView1AdvancedCustomDrawSubItem(Sender: TCustomListView;
  Item: TListItem; SubItem: Integer; State: TCustomDrawState; Stage: TCustomDrawStage;
  var DefaultDraw: Boolean);
begin
  if not (cdsSelected in State) then
    CheckPaintstage(Stage, item.Index, sender.canvas)
  else
  begin
    Sender.Canvas.Font.Color := clHighlightText;
    Sender.Canvas.Brush.Color := clHighlight;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése