我的列表视图应该为指定路径上的每个目录创建一个组,并将每个目录中的图片添加到为其创建的组中;但它会将最后一个目录中的图片添加到每个组中。 任何想法我怎样才能解决这个问题? 谢谢!
private void Form2_Load(object sender, EventArgs e)
{
string path = @"C:\pics\";
string[] tabs_needed = System.IO.Directory.GetDirectories(path);
foreach (string folder in tabs_needed)
{
FileInfo f = new FileInfo(folder);
listBox1.Items.Add(f.Name);
TabPage ghhk = new TabPage(f.Name);
tabControl1.Controls.Add(ghhk);
ListView listView1 = new ListView();
ghhk.Controls.Add(listView1);
listView1.Dock = DockStyle.Fill;
string new_path = path + f.Name;
string[] groups_needed =System.IO.Directory.GetDirectories(new_path);
foreach (string ufolder in groups_needed)
{
FileInfo uf = new FileInfo(ufolder);
string f_path = String.Concat(new_path + @"\" + uf.Name + @"\");
DirectoryInfo dir = new DirectoryInfo(f_path);
ImageList imagelist = new ImageList();
foreach (FileInfo file in dir.GetFiles())
{
try
{
imagelist.Images.Add(Image.FromFile(file.FullName));
}
catch
{
}
}
imagelist.ImageSize = new Size(32, 32);
listView1.View = View.LargeIcon;
ListViewGroup gr1 = new ListViewGroup(uf.Name);
listView1.Groups.Add(gr1);
string tpath = String.Concat(f_path, "gf.txt");
for (int counter = 0; counter < imagelist.Images.Count; counter++)
{
ListViewItem item = new ListViewItem();
item.Text = File.ReadAllLines(tpath).Skip(counter).Take(1).First();
item.ImageIndex = counter;
item.Group = gr1;
listView1.Items.Add(item);
}
listView1.LargeImageList = imagelist;
}
答案 0 :(得分:0)
这种情况正在发生,因为您每次都在foreach循环中实例化ImageList。当您最终将图像列表分配给listView1.LargeImageList时,它只是附加的最终图像列表实例。
您需要将实例化移出foreach循环
ImageList imagelist = new ImageList();
foreach (string ufolder in groups_needed)
{
...
}
由于ImageList不在循环中,您可能还需要更改ImageIndex的逻辑才能使其正常工作。
答案 1 :(得分:0)
你应该替换
listView1.LargeImageList = imagelist;
带
listView1.LargeImageList.Images.AddRange(imagelist.Images.Cast<System.Drawing.Image>().ToArray())
因为您在每个周期都覆盖了图像列表。