2008. december 10., szerda

Change the color of a specific subitem in a TListView


Problem/Question/Abstract:

How to change the color of a specific subitem in a TListView.

Answer:

To change the color of a specific SubItem in a TListView all you have to do is to put some code in the OnCustomDrawSubItems event of the TListView. Your probably thinking of putting the OwnerDraw property of the ListView to True...
don't do this, yes I know normally it should be set to True, but in case of a TListView this is not the case...a bug somewhere in Delphi. Unlike the OnCustomDraw the OnCustomDrawSubItems event is sent no matter the state of the OwnerDraw property.

The OnCustomDrawSubItems is fired prior to drawing the SubItem on the TListView.
To alter the default drawing process at other stages (e.g. after the SubItem is drawn,... .), you must use the OnAdvancedCustomDrawSubItem event.
You can put code here to change the appeance of the SubItems, the ViewStyle of the TListView must be set to vsReport in order for this to function correctly.
Then you can use the canvas of the ListView as a drawing surface.

Let's say you want the font color of a SubItem to turn red whenever it's below is negative then put the following code in the OnCustomDrawSubItems event:


procedure TForm1.ListViewCustomDrawSubItem(
  Sender: TCustomListView; Item: TListItem; SubItem: Integer;
  State: TCustomDrawState; var DefaultDraw: Boolean);
begin
  //Check if the value of the third column is negative,
  //if so change it's font color to Red (clRed).
  if SubItem = 3 then
  try
    if StrToInt(Item.SubItems.Strings[SubItem - 1]) < 0 then
      Sender.Canvas.Font.Color := clRed;
  except
    on EConvertError do
      next;
  end;
end;


Used Parameters:

Sender : Specifies the ListView that owns the SubItems

Item  : Is the current Item being drawn

SubItem: Index of the SubItem of the ListItem (Item) in its SubItems property

State  : Indicates various attributes that affect the way the SubItem is drawn

DefaultDraw: Set it to False to prevent the ListView from adding the SubItem's text after the event handler exits.


Tested with Delphi 6 Professional on Windows 2000 Professional.

Nincsenek megjegyzések:

Megjegyzés küldése