ObjectListView add images to items/objects

2019-04-02 19:38发布

I'm using the ObjectListViewand am trying to add images to my items. I got it to work by looping through all the items and then manually editing the image index per item. I would like to know if this is possible when adding the items. This is the code I have at the moment:

Adding the items

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

Adding the images

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;
}

2条回答
Viruses.
2楼-- · 2019-04-02 19:53

Both your approach and the one I show below will have problems if the list is ever sorted as sorting will change the order of the objects in the list. But really all you have to do is keep track of your object count in your foreach loop.

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++;
}
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-04-02 19:54

It is not entirely clear to me what exactly you try to achieve, but there are several ways to "assign" an image to a row. Note that you probably have to set

myOlv.OwnerDraw = true;

which can also be set from the designer.

If you have a specific image for each of your model objects, its probably best to assign that image directly to your object and make it accessible through a property (myObject.Image for example). Then you can use the ImageAspectName property of any row to specify that property name and the OLV should fetch the image from there.

myColumn.ImageAspectName = "Image";

Another way to do it is using the ImageGetter of a row. This is more efficient if several of your objects use the same image, because you can fetch the image from anywhere you want or even use the assigned ImageList from the OLV by just returning an index.

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

As pointed out, the ImageGetter can also return an index with respect to the ObjectListView's assigned 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;
};

This would be the way to reuse images for multiple objects.

查看更多
登录 后发表回答