【问题标题】:ListView and ImageList Clearing not work?ListView 和 ImageList 清除不起作用?
【发布时间】:2015-05-21 12:56:16
【问题描述】:

我正在开发一个程序,它使用 listView 和 ImageList 来显示本地文件夹中的图像。 我面临的问题是:我的代码有lstView_un.Items.Clear();在导入任何图像之前清除列表视图内容的方法。但它会将先前的内容附加到新加载的或将来加载的图像中。即使我已经通过使用按钮清除列表视图进行了检查,但没有清除任何东西。

有什么问题?请帮我解决问题!

整个代码是:

 lstView_un.Items.Clear();
                DateTime d1 = DateTime.Now;
                DateTime d2 = dtp_unlist.Value;

                TimeSpan t = d1 - d2;
                double NrOfDays = t.TotalDays;


                DateTime dt = DateTime.Now.AddDays(-NrOfDays);
                lstView_un.Items.Clear();
                string imagesPath = @"D:\Face Recognition System\UnknownFace";
                string[] extensions = new[] { ".jpg", ".jpeg", ".png" };
                var allfiles = Directory.GetFiles(imagesPath);
                List<FileInfo> files = new List<FileInfo>();
                foreach (string f in allfiles) files.Add(new FileInfo(f));
                var filesSorted = files.Where(f => extensions.Contains(f.Extension.ToLower()))
                                       .Where(f => f.CreationTime < dt)
                                       .OrderByDescending(f => f.CreationTime);
                this.imageList1.ImageSize = new Size(256, 250);
                this.imageList1.ColorDepth = ColorDepth.Depth32Bit;
                foreach (FileInfo fileInfo in filesSorted)
                {
                    try
                    {
                        this.imageList1.Images.Add(fileInfo.Name,
                                                 Image.FromFile(fileInfo.FullName));
                    }
                    catch
                    {
                        Console.WriteLine(fileInfo.FullName + "  is is not a valid image.");
                    }
                }
                this.lstView_un.View = View.LargeIcon;
                lstView_un.LargeImageList = this.imageList1;
                lstView_un.Items.Clear();
                for (int j = 0; j < this.imageList1.Images.Count; j++)
                {
                    ListViewItem item = new ListViewItem();
                    item.ImageIndex = j;
                    item.Text = imageList1.Images.Keys[j].ToString();
                    this.lstView_un.Items.Add(item);
                }       

【问题讨论】:

  • 添加了什么,ListViewItems 还是图像?您的代码在清除 LV 后重新加载它,所以这似乎是故意的。但是 ImageList 用于填充 LV,并且每次似乎都添加了 ImageList。
  • 似乎每次清除它时,都会添加新项目。那么,问题出在哪里?!
  • 每当我将图像再次加载到 listView 时,之前加载的图像都会附加到 listView。我不知道更多关于 ImageList 的信息,我认为它会追加,有什么方法请帮忙?
  • 在添加更多图像之前,您不会从 ImageList 中删除旧图像

标签: c# listview directory imagelist


【解决方案1】:

每当您清除 lstView_un 时,添加以下 2 行:

        lstView_un.SmallImageList.Images.Clear();
        lstView_un.LargeImageList.Images.Clear();

因为你清除了物品,但没有清除图像。

【讨论】:

    猜你喜欢
    • 2011-12-16
    • 1970-01-01
    • 2016-07-24
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多