【问题标题】:ObjectListView add images to items/objectsObjectListView 将图像添加到项目/对象
【发布时间】:2014-08-25 23:04:42
【问题描述】:

我正在使用 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;
}

【问题讨论】:

  • 我并不完全清楚你想要实现什么,但你的方法似乎是错误的。您是否只想在每个行对象的第一列中显示不同的图像?图像在编译时可用还是需要在运行时获取它们(LoadImage())?
  • @Rev1.0 在我调用此函数之前,正在下载图像并将其放入列表中。我想将这些项目添加到 ObjectListView,但我似乎无法为这些项目提供图像索引,因为我必须添加 objects 而不是 listviewitems
  • 您想为每个项目/对象使用不同的图像吗?

标签: c# winforms objectlistview


【解决方案1】:

我并不完全清楚您到底想达到什么目的,但是有几种方法可以将图像“分配”到一行。请注意,您可能必须设置

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

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

【讨论】:

    【解决方案2】:

    如果列表曾经排序过,那么您的方法和我在下面展示的方法都会出现问题,因为排序会改变列表中对象的顺序。但实际上,您所要做的就是在 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++;
    }
    

    【讨论】:

    • 图标本身不是 ListViewItem,因此我无法为其分配图像索引 :(.
    • 这个类似乎是第三方库的一部分,您是否查看过他们的 Add 方法文档?您可能会超载它,或者他们可能已经有了替代方法?
    • 我查看了他们的文档,但找不到任何东西。这就是我在 Stackoverflow 上发帖的原因。
    • objectlistview.sourceforge.net/cs/… 它谈到了配置......从那个开始?也许您根本不需要排序或添加索引值?无意冒犯,但您可能会“错误地”使用它,我的意思是设计师无意...
    • @FoxyShadoww:JoshW 是正确的,你的方法有缺陷。例如,您永远不会使用底层的 ListViewItem 对象,因为 ObjectListView 故意添加了一个抽象层并且只在内部使用它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    相关资源
    最近更新 更多