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

Yuk*_*uya 0 c# winforms objectlistview

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

添加项目

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

添加图像

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;
}
Run Code Online (Sandbox Code Playgroud)

Rev*_*1.0 7

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

myOlv.OwnerDraw = true;
Run Code Online (Sandbox Code Playgroud)

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

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

myColumn.ImageAspectName = "Image";
Run Code Online (Sandbox Code Playgroud)

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

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

正如所指出的,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;
};
Run Code Online (Sandbox Code Playgroud)

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