【问题标题】:C# How do I loop through Images in a ListboxC#如何遍历列表框中的图像
【发布时间】:2011-04-09 21:44:29
【问题描述】:

我创建了一个图像列表框,我想调整所有图像的大小。我已经掌握了方法,但我似乎无法遍历列表框中的项目:

foreach (Image I in listbox1.items)
{
     Resize(I, x, y)
}

我收到此错误“无法将 system.string 类型的对象转换为 system.drawing.image 类型”。有什么想法吗?

之前我也在列表框选定项上使用图像投射:

Picturebox1.Image = (Image)listbox.selecteditem;

我记得它起作用了,但它不再起作用了。我假设我记错了代码,还有其他选择吗?

【问题讨论】:

  • 向我们展示执行 ListBox.Items.Add 的代码,您在代码的那部分做错了。
  • 将图像放入 ListBox 没有任何意义,它不知道如何显示它们。显然你在里面放了字符串。您的代码无法使用字符串。

标签: c# image casting listboxitem


【解决方案1】:

您的 ListBox.Items.Add 错误。添加 Image 对象,而不是图像或 url 或 Image.ToString() 的字符串路径。

我现在明白了.. 你没有做 ListBox.Items.Add(Image) 因为否则你会在列表框中看到“垃圾”,所以答案是创建一个包装对象:

class ImageWrapper
{
  public Image image;
  public string displayName;
  public override string ToString()
  {
    return displayName;
  }
}

然后做

var iw = new ImageWrapper();
iw.image = <yourImage>;
iw.displayName = "Text for listbox here";
ListBox.Items.Add(iw);

【讨论】:

  • 我已经在列表框中有图像,添加它们不是问题。它从列表框中获取它们。
  • 等等,你是对的。图像永远不会在列表框中只有名称。好吧,那是半天的挫败感。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-11
  • 2023-03-04
  • 2017-12-10
相关资源
最近更新 更多