ObjectListView将图像添加到项目/对象

我正在使用ObjectListView ,我正在尝试将图像添加到我的项目中。 我通过循环遍历所有项目然后手动编辑每个项目的图像索引来使其工作。 我想知道添加项目时是否可行。 这是我目前的代码:

添加项目

 for (int i = 0; i < listName.Count; i++) { games newObject = new games(listName[i], "?"); lstvwGames.AddObject(newObject); } 

添加图像

 foreach (string icon in listIcon) { imglstGames.Images.Add(LoadImage(icon)); // Download, then convert to bitmap } for (int i = 0; i < lstvwGames.Items.Count; i++) { ListViewItem item = lstvwGames.Items[i]; item.ImageIndex = i; } 

我并不完全清楚你想要实现什么,但有几种方法可以将图像“分配”到一行。 请注意,您可能需要设置

 myOlv.OwnerDraw = true; 

也可以从设计师那里设置。

如果每个模型对象都有一个特定的图像,最好将该图像直接分配给对象,并通过属性(例如myObject.Image)访问它。 然后,您可以使用任何行的ImageAspectName属性来指定该属性名称,OLV应该从那里获取图像。

 myColumn.ImageAspectName = "Image"; 

另一种方法是使用一行的ImageGetter。 如果您的几个对象使用相同的图像,这会更有效,因为您可以从任何您想要的地方获取图像,甚至只需返回索引就可以使用OLV中指定的ImageList。

 indexColumn.ImageGetter += delegate(object rowObject) { // this would essentially be the same as using the ImageAspectName return ((Item)rowObject).Image; }; 

正如所指出的,ImageGetter还可以返回与ObjectListView指定的ImageList相关的索引:

 indexColumn.ImageGetter += delegate(object rowObject) { int imageListIndex = 0; // some logic here // decide which image to use based on rowObject properties or any other criteria return imageListIndex; }; 

这将是重用多个对象的图像的方法。

如果列表被排序,您的方法和我在下面显示的方法都会出现问题,因为排序会改变列表中对象的顺序。 但是,您真正要做的就是在foreach循环中跟踪对象计数。

 int Count = 0; foreach (string icon in listIcon) { var LoadedImage = LoadImage(icon); LoadedImage.ImageIndex = Count; imglstGames.Images.Add(LoadedImage); // Download, then convert to bitmap Count++; }