将新图像添加到列表视图时,先前的图像会发生变化

时间:2012-11-14 09:54:27

标签: c# winforms

我对listviews很新。我正试图在列表视图中显示图像。当我添加新项目时,所有以前的项目都会更改为新项目。因此listview具有相同的图像。我完成谷歌搜索仍然无法找到解决方案。请帮帮我。以下是我的代码。

ImageList imageList = new ImageList();

        OpenFileDialog opend1 = new OpenFileDialog();

        opend1.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*";

        opend1.Multiselect = true;

        if (opend1.ShowDialog() == DialogResult.OK)
        {

            listView1.View = View.LargeIcon;

            imageList.ImageSize = new Size(100, 100);

            for (int c = 0; c < opend1.FileNames.Length; c++)
            {

                Image i = Image.FromFile(opend1.FileNames[c].ToString());

                Image img = i.GetThumbnailImage(100, 100, null, new IntPtr());

                imageList.Images.Add(img);

            }

            listView1.LargeImageList = imageList;

            for (int j = 0; j < imageList.Images.Count; j++)
            {

                ListViewItem lstItem = new ListViewItem();

                lstItem.ImageIndex = j;

                listView1.Items.Add(lstItem);
            }

            listView1.Refresh();

        }

1 个答案:

答案 0 :(得分:1)

在WinForms中使用ListView时,您应将所有图片放在ImageList中,并仅将该列表中的图片索引提供给ListViewItems

listView1.LargeImageList = imageList1;
listView1.SmallImageList = imageList2;
listView1.Items.Add("Foo", 0);
listView1.Items.Add("Bar", 1);

创建和填充图片列表ID设计器非常简单。你也可以手动完成:

imageList1.Images.Add(fooImage); // will have index 0
imageList1.Images.Add(barImage); // will have index 1

更新您的代码看起来很好。它是您在申请中的确切代码吗?你只需要简化一点:

listView1.View = View.LargeIcon;
imageList.ImageSize = new Size(100, 100);

foreach(var fileName in opend1.FileNames)
{
    Image img = Image.FromFile(fileName);
    imageList.Images.Add(img.GetThumbnailImage(100, 100, null, new IntPtr()));
}

listView1.LargeImageList = imageList;
for (int index = 0; index < imageList.Images.Count; index++)
     listView1.Items.Add(new ListViewItem() { ImageIndex = index });

listView1.Refresh();