Search code examples
listviewdelphidelphi-7

How to trigger the wrap of items in a ListView in Delphi?


I have a ListView set to vsIcon. Each item is a image with a small text beneath. When I add many items they are wrapped for the width of the ListView (for example 5 items on a row). But when I change its width they are not wrapped again for the new width.

What I tried so far:

  • ListView.Update;

  • ListView.Refresh;

  • ListView.Repaint;

  • function ListView_Arrange(hwndLV: HWND; Code: UINT): Bool;

  • function ListView_RedrawItems(hwndLV: HWND; iFirst, iLast: Integer): Bool;

I haven't tried sorting the items because I don't want them to be sorted. But most of the times they are sorted so sorting wouldn't help much (if it will wrap them, which I don't believe it will).

What I use now:

procedure TForm.WMExitSizeMove(var Message: TMessage);
var
   i, p: Integer;
   ListItem: TListItem;
   c: array of string;
   b: array of Boolean;
begin
   if Showing and (PreviousWidth <> Width) then
   begin
      p := ListView.ItemIndex;
      SetLength(c, ImageList.Count);
      SetLength(b, ImageList.Count);
      for i := 0 to ImageList.Count - 1 do
      begin
         c[i] := ListView.Items[i].Caption;
         b[i] := ListView.Items[i].Selected;
      end;
      ListView.Items.BeginUpdate;
      ListView.Clear;
      for i := 0 to ImageList.Count - 1 do
      begin
         ListItem := ListView.Items.Add;
         ListItem.Caption := c[i];
         ListItem.ImageIndex := i;
         ListItem.Selected := b[i];
      end;
      ListView.ItemIndex := p;
      ListView.Items.EndUpdate;
      SetLength(c, 0);
      SetLength(b, 0);
      PreviousWidth := Width;
   end;
   inherited;
end;

But, as you notice, it's not that fast for a large amount of items. Could you please help me find a better way...?

Thank you.

I use Delphi 7.


Solution

  • The listview can do that for you automatically. Somewhere in your code ( perhaps in formcreate) insert the following:

    listview.IconOptions.AutoArrange := true;
    

    Or you can set it in the properties window as well.