I have found this question which offers this solution on how to add a border to a ListView item:
But I only want to add the border around the image, something like this:
Can this be done?
I have found this question which offers this solution on how to add a border to a ListView item:
But I only want to add the border around the image, something like this:
Can this be done?
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
:
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);
}
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:
Or you could pick the color of the rectangle according to the item state..