1

I have found this question which offers this solution on how to add a border to a ListView item:

enter image description here

But I only want to add the border around the image, something like this:

enter image description here

Can this be done?

Community
  • 1
  • 1
user6088487
  • 189
  • 6

1 Answers1

3

Assuming the LargeIcon View mode, the images are drawn centered and their Size is in the related LargeImageList.ImageSize so something like this should work:

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
    e.DrawDefault = true;
    Size sz = listView1.LargeImageList.ImageSize;
    int w = sz.Width + 4;
    int h = sz.Height + 3;
    int x = (e.Bounds.Width - sz.Width) / 2 + e.Bounds.X - 2;
    int y = e.Bounds.Top + 1 ;
    using (Pen pen = new Pen(Color.Red, 2f))
    {
        pen.Alignment = PenAlignment.Center;
        e.Graphics.DrawRectangle(pen, x, y, w, h);
    }     
}

Here is my ListView:

enter image description here

Of course, if you want the frame to go over the full width (e.Bounds.Width) you can simply restrict only the height as shown..:

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
  e.DrawDefault = true;
  Size sz = listView1.LargeImageList.ImageSize;
  e.Graphics.DrawRectangle(Pens.Red, e.Bounds.X,e.Bounds.Y, e.Bounds.Width,sz.Height + 2);
}

enter image description here

If you want to make the currently focussed item stand out you can do something like this:

Color bCol = e.State.HasFlag(ListViewItemStates.Focused) ?
    Color.LightBlue : listView1.BackColor;
using (SolidBrush brush = new SolidBrush(bCol))
    e.Graphics.FillRectangle(brush, e.Bounds.X, e.Bounds.Y, e.Bounds.Width, sz.Height + 2);

before drawing the Rectangle:

enter image description here

Or you could pick the color of the rectangle according to the item state..

TaW
  • 53,122
  • 8
  • 69
  • 111
  • Hi. I have tried your code and I have a question: is there a way to also highlight the border when selecting an item, because when I select an item, only the image and the text gets selected without the border. – paul Apr 07 '16 at 04:30
  • Yes,, you could add something like this before drawing the rectangle: `if (e.State.HasFlag(ListViewItemStates.Selected) ) e.Graphics.FillRectangle( Brushes.AliceBlue, e.Bounds.X, e.Bounds.Y, e.Bounds.Width, sz.Height + 2);` (Pick your color!) Or you could use the same check and draw the Rectangle in a different Color than Red.. – TaW Apr 07 '16 at 05:16
  • See my updated answer..! – TaW Apr 07 '16 at 08:44