首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在WPF中重写OnDrawItem ListBox

在WPF中重写OnDrawItem ListBox
EN

Stack Overflow用户
提问于 2014-07-28 14:25:51
回答 1查看 662关注 0票数 0

当我使用WinForms时,我使用了带有重写OnDrawItem的ListBox来自定义外观。现在我想在WPF中创建相同的表单。我意识到WPF ListBox没有OnDrawItem方法,所以必须采用另一种方法。下面是我在CustomListBox中使用的WinForms代码的一部分:

代码语言:javascript
复制
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....
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-28 14:48:45

WPF是一个与旧方式完全不同的模式。使用WPF,您不会编写绘制它的代码,而是为您的ListItem定义一个XAML模板/样式。

您希望控件根据属性值更改外观。这是通过触发器实现的:http://www.c-sharpcorner.com/uploadfile/raj1979/styles-using-triggers-in-wpf/

如果您还没有达到这一点,我建议您阅读数据模板的入门部分:http://msdn.microsoft.com/en-us/library/ms742521(v=vs.85).aspx

同时,我也推荐一些像“临WPF”和"WPF Recipes“这样的Apress书籍。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24997460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档