Search code examples
c#winformslistviewownerdrawn

Custom ListView control will not paint when first shown


I have created a custom ListView control to suit my needs and I'm having an issue that causes the ListView not to show any contents (not drawing anything, just white) when the form first loads.

If I resize the form or click on my control (anything that forces a repaint on the ListView) then it shows up as expected.

As a side note, it used to work just fine until I made a small change today and rebuilt the control. I removed all the changes I made and rebuilt again but the issue still happens. Any ideas as to why it will not show up (paint) when the form is first loaded?

This is what I use to do the custom drawing on my custom ListView control...

protected override void OnDrawItem(DrawListViewItemEventArgs e)
{
    Image image = e.Item.ImageList.Images[e.Item.ImageIndex];
    Size textSize = new Size((int)e.Graphics.MeasureString(e.Item.Text, e.Item.Font).Width, (int)e.Graphics.MeasureString(e.Item.Text, e.Item.Font).Height);

    //Get the area of the item to be painted
    Rectangle bounds = e.Bounds;
    bounds.X = 0;
    bounds.Width = this.Width;

    //Set the spacing on the list view items
    int hPadding = 0;
    int vPadding = 0;
    IntPtr padding = (IntPtr)(int)(((ushort)(hPadding + bounds.Width)) | (uint)((vPadding + bounds.Height) << 16));
    SendMessage(this.Handle, (uint)ListViewMessage.LVM_SETICONSPACING, IntPtr.Zero, padding);

    //Set the positions of the image and text
    int imageLeft = (bounds.Width / 2) - (image.Width / 2);
    int imageTop = bounds.Top + 3;
    int textLeft = (bounds.Width / 2) - (textSize.Width / 2);
    int textTop = imageTop + image.Height;
    Point imagePosition = new Point(imageLeft, imageTop);
    Point textPosition = new Point(textLeft, textTop);

    //Draw background
    using (Brush brush = new SolidBrush(e.Item.BackColor))
        e.Graphics.FillRectangle(brush, bounds);

    //Draw selected
    if (e.Item.Selected)
    {
        using (Brush brush = new SolidBrush(m_SelectedColor))
            e.Graphics.FillRectangle(brush, bounds);
    }

    //Draw image
    e.Graphics.DrawImage(image, imagePosition);

    //Draw text
    e.Graphics.DrawString(e.Item.Text, e.Item.Font, new SolidBrush(e.Item.ForeColor), textPosition);
}

I also set the following things in the Constructor of my custom control...

public MyListView()
{
    this.DoubleBuffered = true;
    this.OwnerDraw = true;
    this.View = View.LargeIcon;
    this.Cursor = Cursors.Hand;
    this.Scrollable = false;
}

I also inherit the ListView class...

public class MyListView : ListView
{
    //All my source
}

Solution

  • You need to set the set the control to redraw itself when resized. So add this code in constructor of your control:

    this.ResizeRedraw = true;
    

    enter image description here