0

When I was using WinForms I was using ListBox with overridden OnDrawItem to customize look. Now I wanted to create the same form in WPF. I realized that WPF ListBox does not have OnDrawItem method so it has to be done another way. Here is part of my code of CustomListBox, which I used in WinForms:

Namespace Toolset.Controls
Public Class CustomDrawListBox
    Inherits ListBox
    Dim _1 As Icon = My.Resources._1
    Public Sub New()
        Me.DrawMode = Windows.Forms.DrawMode.OwnerDrawFixed
        Me.ItemHeight = 16
    End Sub

    Protected Overrides Sub OnDrawItem(e As DrawItemEventArgs)
        e.DrawBackground()
        If e.Index >= Me.Items.Count OrElse e.Index <= -1 Then
            Return
        End If

        Dim item As Object = Me.Items(e.Index)
        If item Is Nothing Then
            Return
        End If

        Dim text As String = item.ToString()
        Dim stringSize As SizeF = e.Graphics.MeasureString(text, Me.Font)
        If DTun4.Form1.status.ContainsKey(text) Then
            If DTun4.Form1.status(text).status = 0 Then
                e.Graphics.DrawIcon(_0, 0, e.Bounds.Y)
                e.Graphics.DrawString(text, Me.Font, New SolidBrush(Color.Red), New PointF(20, e.Bounds.Y + (e.Bounds.Height - stringSize.Height) / 2))
                e.Graphics.DrawString("999", Me.Font, Brushes.Red, New PointF(e.Bounds.Right - 25, e.Bounds.Y + (e.Bounds.Height - stringSize.Height) / 2))
            ElseIf DTun4.Form1.status(text).status = 1 Then
                e.Graphics.DrawIcon(_1, 0, e.Bounds.Y)
                e.Graphics.DrawString(text, Me.Font, New SolidBrush(Color.YellowGreen), New PointF(20, e.Bounds.Y + (e.Bounds.Height - stringSize.Height) / 2))
                e.Graphics.DrawString("N/A", Me.Font, Brushes.YellowGreen, New PointF(e.Bounds.Right - 25, e.Bounds.Y + (e.Bounds.Height - stringSize.Height) / 2))
 ....rest of long code....
Disa
  • 630
  • 13
  • 42
  • 1
    HighCore, I know you probably mean well, but please try to be objective and create a positive environment here instead of trashing people's questions. Closing a question in this manner is in poor taste. – djdanlib Aug 01 '14 at 18:11

1 Answers1

2

WPF is a completely different model than the old way. With WPF, you don't write code that draws it, you define a XAML template / style for your ListItem.

You want the control to change appearance based upon a property value. That's accomplished with a trigger: http://www.c-sharpcorner.com/uploadfile/raj1979/styles-using-triggers-in-wpf/

If you haven't gotten to this point yet, I recommend going through the primer on data templating as well: http://msdn.microsoft.com/en-us/library/ms742521(v=vs.85).aspx

Also, I recommend the Apress books like "Pro WPF" and "WPF Recipes".

djdanlib
  • 21,449
  • 1
  • 20
  • 29