Code Repo    |     RSS
MD's Technical Sharing



Sunday, August 3, 2008

Customize Listview Item Forecolor & Backcolor

By setting ListView.OwnerDraw = true and Capture the DrawItem event.

http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.drawitem.aspx


The following code supports custom draw of a Listview in details view. Each item has its own text and image.


Private Sub ListViewContacts_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawListViewItemEventArgs) 'Handles ListViewContacts.DrawItem
'draw the text and the item icon
Dim itemImage As Image = e.Item.ImageList.Images(e.Item.ImageIndex)
Dim offset1 As Integer = 15 'offset between left margin and icon
Dim offset2 As Integer = 5 'offset between icon and text

'Debug.WriteLine(e.Item.Text + ": " + e.State.ToString)

If (e.State And ListViewItemStates.Selected) > 0 And (e.State And ListViewItemStates.Focused) > 0 Then
' Draw the background for a selected & focused item.
e.Graphics.FillRectangle(Brushes.RoyalBlue,
New RectangleF(e.Bounds.X + offset1 + itemImage.Width + offset2, e.Bounds.Y, e.Graphics.MeasureString(e.Item.Text, Me.ListViewContacts.Font, Me.ListViewContacts.Width).Width, e.Bounds.Height))

'draw the item text
e.Graphics.DrawString(e.Item.Text,
Me.ListViewContacts.Font, Brushes.White, e.Bounds.X + itemImage.Width + offset1 + offset2, e.Bounds.Y)
'ElseIf (e.State And ListViewItemStates.Selected) > 0 And (e.State And ListViewItemStates.Focused) = 0 Then
' ' Draw the background for a selected item not having focused
' e.Graphics.FillRectangle(Brushes.LightGray, New RectangleF(e.Bounds.X + offset1 + itemImage.Width + offset2, e.Bounds.Y, e.Graphics.MeasureString(e.Item.Text, Me.ListViewContacts.Font, Me.ListViewContacts.Width).Width, e.Bounds.Height))

' 'draw the item text
' e.Graphics.DrawString(e.Item.Text, Me.ListViewContacts.Font, Brushes.White, e.Bounds.X + itemImage.Width + offset1 + offset2, e.Bounds.Y)
Else
' Draw the background for an unselected item.
Dim brush As New LinearGradientBrush(e.Bounds, Color.White, Color.White, LinearGradientMode.Horizontal)
Try
e.Graphics.FillRectangle(brush, e.Bounds)
Finally
brush.Dispose()
End Try

'draw the item text
e.Graphics.DrawString(e.Item.Text,
Me.ListViewContacts.Font, Brushes.Black, e.Bounds.X + itemImage.Width + offset1 + offset2, e.Bounds.Y)
End If

e.Graphics.DrawImage(itemImage,
New PointF(e.Bounds.X + offset1, e.Bounds.Y))

'use the default drawing
'e.DrawDefault = True
End Sub

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.