2009-12-11 25 views

回答

10

ListView控件本身不支持子項目中的圖像。最簡單的做法是切換到DataGridView並使用DataGridViewImageColumn。如果這不可行,那麼您需要使用ListView控件中的自定義繪圖支持自己繪製圖標。要執行此操作,請設置ListView.OwnerDraw = true並處理ListView.DrawSubItemListView.DrawColumnHeader事件。

private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e) 
{ 
    // Only interested in 2nd column. 
    if (e.Header != this.columnHeader2) 
    { 
     e.DrawDefault = true; 
     return; 
    } 

    e.DrawBackground(); 
    var imageRect = new Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Height, e.Bounds.Height); 
    e.Graphics.DrawImage(SystemIcons.Information.ToBitmap(), imageRect); 
} 

private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e) 
{ 
    e.DrawDefault = true; 
} 
+0

爲什麼不只是'var imageRect = e.Bounds;'它是一個值類型,所以值將被複制並且不被引用使得它們可以安全地處理。 – ja72

+0

在現實世界的用法中,您可能需要調整imageRect以考慮對齊,填充和/或子項中包含的其他內容。 –

2

繼承ListView和繪製自己的圖標。

public class MyListView : ListView 
{ 
    protected override void OnDrawSubItem(System.Windows.Forms.DrawListViewSubItemEventArgs e) 
    { 
     base.OnDrawSubItem(e); 
    } 
} 
6

使用的P/Invoke和發送LVM_SETITEM消息列表視圖(您應設置在創建控件或通過LVM_SETEXTENDEDLISTVIEWSTYLE LVS_EX_SUBITEMIMAGES風格),指定的分項指數和相應的圖像索引。您需要爲插入的每個列表項目執行此操作。

0

圖標顯示在「第一個」列中,這也是鍵盤前綴搜索的基礎。一種可能的解決方案可能是通過將第一列的DisplayIndex設置爲其他值來對列進行重新排序。

listView1.Columns[0].DisplayIndex = 1; 

這當然只適用於只需要一列中的圖標。