2013-03-26 17 views
0

C#的ListView中有後續加可用的方法添加一個條目如何添加ListViewItem的具有自己獨特的形象

public virtual ListViewItem Add(ListViewItem value) 
public virtual ListViewItem Add(string text) 
public virtual ListViewItem Add(string text, int imageIndex) 
public virtual ListViewItem Add(string text, string imageKey) 
public virtual ListViewItem Add(string key, string text, int imageIndex) 
public virtual ListViewItem Add(string key, string text, string imageKey) 

場景:我有一個ListView和希望動態用自己獨特的添加ListViewItems第一列中的圖像。此外,這些圖像可以根據狀態更改進行更新

問題:您會如何做到這一點?

代碼我與

 private void AddToMyList(SomeDataType message) 
     { 
      string Entrykey = message.ID; 

      //add its 1 column parameters 
      string[] rowEntry = new string[1]; 
      rowEntry[0] = message.name; 

      //make it a listviewItem and indicate its row 
      ListViewItem row = new ListViewItem(rowEntry, (deviceListView.Items.Count - 1)); 

      //Tag the row entry as the unique id 
      row.Tag = Entrykey; 

      //Add the Image to the first column 
      row.ImageIndex = 0; 

      //Add the image if one is supplied 
      imagelistforTypeIcons.Images.Add(Entrykey, message.marker.markerIcon); 

      //finally add it to the device list view 
      typeListView.Items.Add(row); 

     } 

回答

1

工作有兩件事情你需要做的

  • 添加圖片到圖像列表,如果它不是在它已經
  • 創建新ListViewItem並從之前指向它的圖像

它可能是這樣的,根據您的代碼:

// Add markerIcon to ImageList under Entrykey 
imagelistforTypeIcons.Images.Add(Entrykey, message.marker.markerIcon); 
// Use icon from ImageList which is stored under Entrykey 
ListViewItem row = new ListViewItem(rowEntry); 
row.ImageKey = Entrykey; 
// Do whatever else you need afterwards 
row.Tag = Entrykey; 
.... 

問題在你的代碼有問題(沒有實際嘗試它)看起來是在ImageIndex要分配。

  • 要添加新的圖像,以一個圖像列表,而是從一個不同的
  • 您所提供的圖像索引在構造函數,但隨後將其設置爲0(爲什麼?)
  • 你分配一個圖像ListViewRow首先提供了錯誤的圖像索引,因爲您在添加新圖像之前計算了圖像列表中最後一張圖像的索引。

所以,你的代碼也可能是罰款是這樣的:

// Add markerIcon to ImageList under Entrykey 
imagelistforTypeIcons.Images.Add(Entrykey, message.marker.markerIcon); 
// Use icon from ImageList which is stored under Entrykey 
ListViewItem row = new ListViewItem(rowEntry); 
row.ImageIndex = imagelistforTypeIcons.Items.Count - 1; 
// Do whatever else you need afterwards 
row.Tag = Entrykey; 
+0

ListViewItem的行=新的ListViewItem(rowEntry,EntryKey);你不能這樣做。沒有滿足的重載方法。 rowEntry是我的Listveiw項目 – stackoverflow 2013-03-26 19:25:54

+1

我已經更新了答案。您可以通過屬性設置「ImageIndex」和「ImageKey」,以便您可以爲構造函數提供字符串數組參數。 – 2013-03-26 19:43:35

+0

謝謝,這真的救了我的一天! – stackoverflow 2013-03-26 19:52:24