2

I'm building a custom ListView control for a specific purpose/application wherein I have to display gallery. For this I'm using owner drawn process to manually draw images in the ListView.

My images in ListView will be 128x128 pixels so I've assigned a blank ImageList control (with 128x128 image dimensions) as image list to ListView to automatically define the item size.

enter image description here

This works fine for me up till now. But I need to eliminate the space between the item rows (as shown in the example image). My goal is to make the custom listview look like an images grid. I'm not worried about the space on the left and right of items, just need to get rid of space between the rows so that it looks like a continuous grid.

Any help is appreciated. Thanks.

Faraz Azhar
  • 562
  • 9
  • 28
  • 2
    If you switch to OwnerDraw (where you draw the rectangle contents) you can switch the view to Tile. Or try [.NET ListView row padding](https://stackoverflow.com/q/57849/719186) – LarsTech Jul 10 '18 at 15:56
  • You can actually draw beyond the e.Bounds rectangle. But using Tile is probably the simplest and best solution, although it will still have small gaps. – TaW Jul 10 '18 at 15:58
  • @LarsTech The Tile approach did fix the problem of space in between rows, but the now I cannot change the item size. The post you referred only works in LargeIcon view mode. --EDIT: I just noticed the TileSize property. Thanks. – Faraz Azhar Jul 10 '18 at 16:27
  • 1
    @TaW Yes I experimented with drawing beyond the Bounds dimension, but then the problem occurs on the last row; the drawing goes beyond the ListView's bounds. – Faraz Azhar Jul 10 '18 at 16:28

1 Answers1

1

Switching to Tile View and performing your own drawing can avoid the row spacing issue:

listView1.TileSize = new Size(128, 128);
listView1.View = View.Tile;
listView1.OwnerDraw = true;
listView1.DrawItem += listView1_DrawItem;

and a simple drawing routine:

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e) {
  Color textColor = SystemColors.WindowText;
  if (e.Item.Selected) {
    if (listView1.Focused) {
      textColor = SystemColors.HighlightText;
      e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);
    } else if (!listView1.HideSelection) {
      textColor = SystemColors.ControlText;
      e.Graphics.FillRectangle(SystemBrushes.Control, e.Bounds);
    }
  } else {
    using (SolidBrush br = new SolidBrush(listView1.BackColor)) {
      e.Graphics.FillRectangle(br, e.Bounds);
    }
  }

  e.Graphics.DrawRectangle(Pens.Red, e.Bounds);
  TextRenderer.DrawText(e.Graphics, e.Item.Text, listView1.Font, e.Bounds,
                        textColor, Color.Empty,
                        TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
}

Result:

enter image description here

LarsTech
  • 80,625
  • 14
  • 153
  • 225