2013-05-15 15 views
1

當無法找到ListViewItem的ImageKey時,是否有內置的方式來使用默認圖像?如何在無法找到圖像鍵的情況下設置ListViewItem的默認圖像

我有一個ImageList:

  • car.png
  • house.png
  • 爲Default.png

而一個ListViewItem的

var item = new ListViewItem("Item1"); 
item.ImageKey = "computer.png"; 

默認情況下的ListView在這種情況下不顯示圖像。是否有可能顯示「default.png」

回答

2

這應該做到這一點(雖然可能有一個更優雅的方式)。您可能需要根據您填充ListView的方式進行調整。基本的代碼是這樣的:

string imageKey = "DefaultKey"; 
string someOtherKey = "SomeOtherKey"; 
if (lv.SmallImageList.Images.ContainsKey("SomeOtherKey")) 
{ 
    imageKey = someOtherKey; 
} 
var item = new ListViewItem("Item1"); 
item.ImageKey = imageKey; 

需要注意的是,這取決於你如何填充您的列表中,這可能是更好的拉出成返回相應的鍵的功能:雖然是

string getImageKey(string candidateKey) 
{ 
    if (lvAzureDirectory.SmallImageList.Images.ContainsKey(candidateKey)) 
    { 
     return candidateKey; 
    } 
    else 
    { 
     return "DefaultKey"; 
    } 
} 
+0

不是我期望得到的答案,而是我會這樣做的方式。 – dwonisch

相關問題