【问题标题】:Forms - Add a picture to every item in a ListView表单 - 将图片添加到 ListView 中的每个项目
【发布时间】:2017-08-16 16:33:18
【问题描述】:

如何在 C# Forms 中向 ListView 添加图片?
我的程序获取目录的所有子文件夹,并能够在 ListView 中显示名称。
但我无法为每个列表视图项添加文件夹图标。
这是我到目前为止尝试过的代码:

string storedir = 
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + 
"\\myfolder";

ImageList imgl = new ImageList();
//Get the folder icon from resources
imgl.Images.Add(Properties.Resources.folder);

DirectoryInfo dir = new DirectoryInfo(storedir);
foreach (DirectoryInfo getdirs in dir.GetDirectories("*.*")) {
    ListViewItem lItem = listView1.Items.Add(getdirs.Name, imgl.Images.Count - 1);
}


没有成功:

谁能帮帮我?

编辑:

现在可以了。感谢@Gusman 和@LarsTech! 我在表单中添加了一个 ImageList 控件并将其命名为“imgl”。然后我在 ListView 控件上将它设置为 Small- 和 LargeImageList,最后我删除了

ImageList imgl = new ImageList();

谢谢!

【问题讨论】:

  • 图片的索引必须以0为基础,所以不用imgl.Images.Count使用imgl.Images.Count - 1
  • ListView控件需要通过LargeImageList和SmallImageList属性引用你的图片列表。
  • 好的,我添加了“ - 1”,但仅此一项并没有改变任何东西(也更新了帖子),@LarsTech 这两个选项,Large 和 SmallImageList 都不允许我选择任何东西。它只是说“(无)”
  • 补充:我添加了一个 ImageList 控件并将其命名为 imgl。现在可以了!谢谢! :)
  • 可以使用图像列表添加最大 256x256 的图像。对于较大的图像,您需要进行所有者绘制列表视图。 - 如果您对答案感到满意,请考虑accepting it..!

标签: c# winforms listview


【解决方案1】:

正如 Lars 在评论中所说,您必须将 LargeImageList 属性设置为 imagelist 的引用

所以,像这样分配图像列表:

listView1.LargeImageList = imgl;

接下来,您必须为图像添加从 0 开始的索引。在您的图像列表中,0 表示第一张图像、1 秒等。类似这样的东西(无需通过指定最后一个索引来访问列表中的最后一张图像):

foreach (DirectoryInfo getdirs in dir.GetDirectories("*.*")) {
    ListViewItem lItem = listView1.Items.Add(getdirs.Name, 0);

【讨论】:

    猜你喜欢
    • 2020-06-27
    • 2017-09-19
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多