C# 使用 View.Details 用 ImageList 填充 ListView

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10228922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:58:44  来源:igfitidea点击:

Filling a ListView with an ImageList using View.Details

c#.netlistviewimagelistdetailview

提问by cheeseman

Having an issue loading icons in to my listview. I can get the images to work in large view but not in details, not quite sure what I am doing wrong.

将图标加载到我的列表视图时出现问题。我可以让图像在大视图下工作,但不能在细节上工作,不太确定我做错了什么。

private void CreateList()
{
    listView1.View = View.Details;

    listView1.Columns.Add("Icon", -2, HorizontalAlignment.Center);

    listView1.Columns.Add("Name", -2, HorizontalAlignment.Left);

    imageList1.ImageSize = new Size(32, 32);

    for (int i = 0; i < subKeys.Length; i++)
    {
        if (subKeys[i].Contains("App"))
        {
            imagePath = subKeys[i];

            if (System.IO.File.Exists(imagePath))
            {
                imageList1.Images.Add(Image.FromFile(imagePath));
            }

            numberOfImages++;
        }
    }

    listView1.StateImageList = this.imageList1;
}

采纳答案by David Anderson

Change

改变

listView1.StateImageList = this.imageList1;

To

listView1.SmallImageList = this.imageList1;

And make sure that you are setting the ImageIndex, or ImageKeyproperties for each ListItem.

并确保为每个 ListItem设置ImageIndex, 或ImageKey属性。

listItem.ImageIndex = 0; // or,
listItem.ImageKey = "myImage";

回答by Mitja Bonca

Try this code:

试试这个代码:

        DirectoryInfo dir = new DirectoryInfo(@"c:\myPicutures"); //change and get your folder
        foreach (FileInfo file in dir.GetFiles())
        {
            try
            {
                this.imageList1.Images.Add(Image.FromFile(file.FullName));
            }
            catch{
                Console.WriteLine("This is not an image file");
            }
        }
        this.listView1.View = View.LargeIcon;
        this.imageList1.ImageSize = new Size(32, 32);
        this.listView1.LargeImageList = this.imageList1;
        //or
        //this.listView1.View = View.SmallIcon;
        //this.listView1.SmallImageList = this.imageList1;

        for (int j = 0; j < this.imageList1.Images.Count; j++)
        {
            ListViewItem item = new ListViewItem();
            item.ImageIndex = j;
            this.listView1.Items.Add(item);
        }

You can even add 2nd column, and "add" a file name.

您甚至可以添加第二列,并“添加”一个文件名。