ListView.DrawItem 事件

定义

在绘制 ListView 并且 OwnerDraw 属性设置为 true 时发生。

public:
 event System::Windows::Forms::DrawListViewItemEventHandler ^ DrawItem;
public event System.Windows.Forms.DrawListViewItemEventHandler DrawItem;
public event System.Windows.Forms.DrawListViewItemEventHandler? DrawItem;
member this.DrawItem : System.Windows.Forms.DrawListViewItemEventHandler 
Public Custom Event DrawItem As DrawListViewItemEventHandler 

事件类型

示例

下面的代码示例提供了事件处理程序的 DrawItem 实现。 有关完整示例,请参阅 OwnerDraw 参考主题。

// Draws the backgrounds for entire ListView items.
private void listView1_DrawItem(object sender,
    DrawListViewItemEventArgs e)
{
    if ((e.State & ListViewItemStates.Selected) != 0)
    {
        // Draw the background and focus rectangle for a selected item.
        e.Graphics.FillRectangle(Brushes.Maroon, e.Bounds);
        e.DrawFocusRectangle();
    }
    else
    {
        // Draw the background for an unselected item.
        using (LinearGradientBrush brush =
            new LinearGradientBrush(e.Bounds, Color.Orange,
            Color.Maroon, LinearGradientMode.Horizontal))
        {
            e.Graphics.FillRectangle(brush, e.Bounds);
        }
    }

    // Draw the item text for views other than the Details view.
    if (listView1.View != View.Details)
    {
        e.DrawText();
    }
}
' Draws the backgrounds for entire ListView items.
Private Sub listView1_DrawItem(ByVal sender As Object, _
    ByVal e As DrawListViewItemEventArgs) _
    Handles listView1.DrawItem

    If Not (e.State And ListViewItemStates.Selected) = 0 Then

        ' Draw the background for a selected item.
        e.Graphics.FillRectangle(Brushes.Maroon, e.Bounds)
        e.DrawFocusRectangle()

    Else

        ' Draw the background for an unselected item.
        Dim brush As New LinearGradientBrush(e.Bounds, Color.Orange, _
            Color.Maroon, LinearGradientMode.Horizontal)
        Try
            e.Graphics.FillRectangle(brush, e.Bounds)
        Finally
            brush.Dispose()
        End Try

    End If

    ' Draw the item text for views other than the Details view.
    If Not Me.listView1.View = View.Details Then
        e.DrawText()
    End If

End Sub

注解

此事件允许使用所有者绘图自定义控件的外观 ListView 。 仅当 属性设置为 true时,OwnerDraw才会引发该属性。 有关所有者绘图的详细信息,请参阅 OwnerDraw 属性参考主题。

每个DrawItemListView项都可能发生该事件。 当 属性 View 设置为 View.Details时, DrawSubItem 也会发生 和 DrawColumnHeader 事件。 在这种情况下,可以处理 DrawItem 事件以绘制所有项(如背景)共有的元素,并处理 DrawSubItem 事件以绘制单个子项的元素,例如文本值。 还可以仅使用两个事件中的一个来绘制控件中的所有 ListView 项,但这可能不太方便。 若要在详细信息视图中绘制列标题,必须处理 DrawColumnHeader 事件。

注意

由于基础 Win32 控件中的 bug, DrawItem 当鼠标指针移动到该行上时,该事件在详细信息视图中每行中不附带 DrawSubItem 一次事件,从而导致事件处理程序中 DrawSubItem 绘制的任何内容被事件处理程序中 DrawItem 绘制的自定义背景所绘制。 有关在发生额外事件时使每行失效的解决方法,请参阅参考主题中的 OwnerDraw 示例。 另一种解决方法是将所有自定义绘图代码放入事件处理程序中 DrawSubItem ,并仅当值为 0 时 DrawListViewSubItemEventArgs.ColumnIndex ,才绘制整个项的背景 (包括子项) 。

有关处理事件的详细信息,请参阅 处理和引发事件

适用于

另请参阅