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 屬性參考主題。

每個 ListView 專案都可能發生此 DrawItem 事件。 View當 屬性設定為 View.Details 時, DrawSubItem 也會發生 和 DrawColumnHeader 事件。 在此情況下,您可以處理 DrawItem 事件來繪製所有專案通用的專案,例如背景,並處理 DrawSubItem 事件來繪製個別子專案的元素,例如文字值。 您也可以只使用兩個事件之一來繪製 控制項中的所有 ListView 專案,但這可能較不方便。 若要在詳細資料檢視中繪製資料行標頭,您必須處理 DrawColumnHeader 事件。

注意

由於基礎 Win32 控制項中的 Bug,因此當滑鼠指標移到資料列上方時, DrawItem 事件會在詳細資料檢視中每一個資料列一次隨附 DrawSubItem 事件,導致事件處理常式中 DrawSubItem 繪製的任何專案,都會由事件處理常式中 DrawItem 繪製的自訂背景繪製出來。 如需因應措施,請參閱參考主題中的 OwnerDraw 範例,此因應措施會在發生額外事件時使每個資料列失效。 替代的因應措施是將所有自訂繪圖程式碼放在事件處理常式中 DrawSubItem ,並繪製整個專案的背景 (只有在值為 0 時 DrawListViewSubItemEventArgs.ColumnIndex ,才會包含子專案) 。

如需處理事件的詳細資訊,請參閱 處理和引發事件

適用於

另請參閱