I have a ListView in a C# WinForms project with OwnerDraw
set to true. I'm populating both LargeIcon and List views, as well as the LargeImageList
and SmallImageList
properties (both of which have only a single image as all items display the same icon).
List view is drawing without issue:
LargeIcon view displays correctly initially:
but leaves background artifacts as the selected item changes (doesn't matter if clicking or using the arrow keys):
Also, as shown, there's an issue with the text being cut off if too long, but that's a secondary concern.
Here is my DrawItem event (ORANGE
and WHIE
are color constant values declared elsewhere):
private void ListView_DrawItem( object sender, DrawListViewItemEventArgs e ) {
ListView list = sender as ListView;
if( e.Item.Selected ) {
e.Graphics.FillRectangle( new SolidBrush( ORANGE ), e.Bounds );
} else {
e.Graphics.FillRectangle( new SolidBrush( WHITE ), new Rectangle( e.Bounds.Location, e.Bounds.Size ) );
}
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
if( list.View == View.List ) {
e.Graphics.DrawImage( list.SmallImageList.Images[0], new Point( e.Bounds.Left + 4, e.Bounds.Top ) );
e.Graphics.DrawString( e.Item.Text, new Font( "SegoeUI", 10, FontStyle.Regular ), new SolidBrush( Color.Black ), new PointF( e.Bounds.Left + 22, e.Bounds.Top + 1 ) );
} else if( list.View == View.LargeIcon ) {
e.Graphics.DrawImage( list.LargeImageList.Images[0], new Point( e.Bounds.Left + ( ( e.Bounds.Width - 32 ) / 2 ), e.Bounds.Top ) );
e.Graphics.DrawString( e.Item.Text, new Font( "SegoeUI", 10, FontStyle.Regular ), new SolidBrush( Color.Black ), new RectangleF( new PointF( e.Bounds.Left, e.Bounds.Top + 34 ), new SizeF( e.Bounds.Width, e.Bounds.Height - 34 ) ), new StringFormat { Alignment = StringAlignment.Center } );
}
}
A lot of this has been trial and error, including the geometry calculations and using the TextRenderingHint
, which I did to get font smoothing, but I'm not sure I'm using the right value.
I last did an owner-drawn ListView years ago, but I guess I'm rusty now, and for the life of me can't make it work. Any pointers would be greatly appreciated.