ListView <--> ImageList Will Not Sync

2019-08-14 18:02发布

I am using a ListView to load and display thumbnails for image files. The "Name" or key that I'm using for each ListViewItem is the fully-qualified file name.

I have also created an ImageList which loads thumbnails of those files using the same key. I've assigned this ImageList as the "SmallImageList" property of the ListView.

When I add and remove files, I add and remove them by key from both the ListView.Items and the ImageList.Images collections.

All of this works fine when loading many images. However, when I try deleting a given key, the ListView control no longer displays the thumbnails properly.

Before and after deleting an item:

Before After

When I analyze both collection arrays in memory during debugging, the keys line up perfectly.

Code used:

// Add the images from an array of paths
foreach (string xFile in files)
{
    thumbnails_imageList.Images.Add(xFile, images[xFile]);
    files_lst.Items.Add(xFile, Path.GetFileNameWithoutExtension(xFile), xFile);
}

// Delete the selected key(s)
foreach (ListViewItem xItem in files_lst.SelectedItems)
{
    files_lst.Items.Remove(xItem);
    thumbnails_imageList.Images.RemoveByKey(xItem.Name);
}

1条回答
Summer. ? 凉城
2楼-- · 2019-08-14 18:38

what happens is clear, if you have a ListViewItem bound to image index 5 and you delete the image in position 4, the 5 shifts down to 4 and the item keeps a reference to the 5 so does not show any image.

I think you should not remove the images from the ImageList when you remove the selected ListView items.

查看更多
登录 后发表回答