Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何设置ListViewItem';如果找不到图像键,则为默认图像_C#_Winforms - Fatal编程技术网

C# 如何设置ListViewItem';如果找不到图像键,则为默认图像

C# 如何设置ListViewItem';如果找不到图像键,则为默认图像,c#,winforms,C#,Winforms,当无法找到ListViewItem的ImageKey时,是否有一种内置的方法来使用默认图像 我有一个图像列表: car.png house.png default.png 和一个ListViewItem var item = new ListViewItem("Item1"); item.ImageKey = "computer.png"; 在这种情况下,默认情况下ListView不显示图像。是否有可能显示“default.png”这应该可以做到(尽管可能有更优雅的方式)。您可能需要对此进

当无法找到ListViewItem的ImageKey时,是否有一种内置的方法来使用默认图像

我有一个图像列表:

  • car.png
  • house.png
  • default.png
和一个ListViewItem

var item = new ListViewItem("Item1");
item.ImageKey = "computer.png";
在这种情况下,默认情况下ListView不显示图像。是否有可能显示“default.png”

这应该可以做到(尽管可能有更优雅的方式)。您可能需要对此进行调整,以适应填充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";
    }
}

虽然这不是我期望得到的答案,但我会这样做。