更新单个ListView项

时间:2015-12-15 18:05:34

标签: c#

我有一个ListView加载如下:

ImageList imgList = new ImageList();
textureViewer.LargeImageList = imgList;
textureViewer.LargeImageList.ImageSize = new System.Drawing.Size(50,50);

foreach (Texture t in textureList)
{
     string imgKey = System.IO.Path.GetFileNameWithoutExtension(t.imageName);
     imgList.Images.Add(imgKey, t.image);

     ListViewItem item = new ListViewItem();
     item.Text = imgKey;
     item.ImageKey = imgKey;
     textureViewer.Items.Add(item);
}

我的程序允许您随时更改图像,因此我必须使用您选择的新图片更新ListView。我通过重用上面的代码来更新它,但我希望能够仅更新所选图片,因为我不想重新加载和刷新列表视图。 我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

您可以使用Tag实例上的ListViewItem属性。将Tag设置为有意义的内容,例如imgKey。然后,您可以通过迭代项目并将Tag与要更新的imgKey进行比较来找到要更新的正确ListViewItem。您也可以使用LINQ,textureViewer.Items.OfType<ListViewItem>.Where(i => i.Tag.Equals(match));

您可以使用此逻辑更新指向同一标记的多个项目。

请记住将新的imgKey和图片添加到图片列表中,并更新Tag上的ListViewItem属性,否则您可能会遇到异常/错误。< / p>

如果imgKey没有改变而只改变了实际图像,那么你应该做的就是更新图像列表和Invalidate列表视图。

答案 1 :(得分:0)

这是一个棘手的问题,因为我的思维方式只是通过图像列表实例中的键更新图像集合,然后调用Refresh的{​​{1}} ...但它不起作用。

工作方式:

  1. 按键从图像集中删除图像。
  2. 使用相同的密钥向图像集添加新图像。
  3. 我假设您要使用密钥

    更新图像
    ListView

    我已添加对Image newImage = ... // new image string imgKey = ... // the key of the image to update // find the previous image by key Image previousImage = imgList.Images[imgList.Images.Keys.IndexOf("imgKey")]; // remove the previous image from the collection imgList.Images.RemoveByKey(imgKey); // add a new image imgList.Images.Add(imgKey, newImage); // dispose the previous image previousImage.Dispose(); 方法的调用。