c# - 如何使用 C# 将图标设置为 ListView 的子项?

标签 c#

我有 ListView 控件。可以从 imagelist 中选择 imageindex 并将图像设置为 listview item 但如何将 icon 设置为 listview subitem

        listView1.Columns.Add("Objects");
        listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
        listView1.SmallImageList = imageList1;
        listviewitem = new ListViewItem("David", 1);
        listviewitem.SubItems.Add("John");
        this.listView1.Items.Add(listviewitem);
        listView1.View = View.Details;

我想将图像设置为子项 - 名为“John”。

最佳答案

ListViewItem 只能有一个 图像,并且它必须与主 ListViewItem 一起使用(即与 SubItems[ 0].)

但是您可以改变显示顺序,这样您就可以在任何列中显示图像。

listView1.Columns[0].DisplayIndex = 2;

enter image description here

但是,当然您也可以所有者绘制 ListView 并包含具有任意数量 子项目!这将需要更多的代码行(大约十几行),但它允许您以几乎任何您喜欢的方式设置 ListView 的样式..

这是一个在所有列中都有(随机)图像的示例:

enter image description here

要获得此结果,您需要...:

  • 为 LV 设置 OwnerDraw = true
  • 为所有项目设置 UseItemStyleForSubItems = false
  • 对所有三个 Drawxxx 事件进行编码。
  • 决定如何存储对第二个(等)图像的引用,因为 SubItem 类没有 ImageIndex

您可以使用 SubItemTag 来保存 ImageIndex 编号,或者,如果您不需要 文本,您可以设置文本,以便将其用作索引,甚至用作 ImageList 中的Key

其中两个事件很简单:

private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
    e.DrawDefault = true;
}

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
    e.DrawDefault = true;
}

第三个是你实际画画的地方:

    private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
    {
        e.DrawBackground();
        Size sz = listView1.SmallImageList.ImageSize;
        int idx = 0;
        if (e.SubItem.Tag != null) idx = (int)e.SubItem.Tag;
        Bitmap bmp = (Bitmap)listView1.SmallImageList.Images[idx];
        Rectangle rTgt = new Rectangle(e.Bounds.Location, sz);
        bool selected = e.ItemState.HasFlag(ListViewItemStates.Selected);
        // optionally show selection:
        if (selected ) e.Graphics.FillRectangle(Brushes.CornflowerBlue, e.Bounds);

        if (bmp != null) e.Graphics.DrawImage(bmp, rTgt);

        // optionally draw text
        e.Graphics.DrawString(e.SubItem.Text, listView1.Font,
                              selected  ? Brushes.White: Brushes.Black,
                              e.Bounds.X + sz.Width + 2, e.Bounds.Y + 2);
    }

当然,您会希望将图像和文本的绘制限制在您需要的那些列中。添加更多检查应该很简单。

关于c# - 如何使用 C# 将图标设置为 ListView 的子项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46128498/

相关文章:

c# - 如何正确返回值?

c# - IdentityServer4 - 缺少来自 Google 的声明

c# - c# 中未初始化结构与未初始化类的大小是多少?

c# - 路由参数在 WebApi 中不起作用

c# - VB 函数 IsObject 的 C# 等效项是什么?

c# - 标记为 Content -> Copy Always 的文件未被复制

c# - 无法将参数传递给存储过程: parameters not supplied

c# - 系统.IO.FileNotFoundException : Could not load file or assembly 'X' or one of its dependencies when deploying the application

c# - Thread.Sleep() 窃取调试器焦点

c# - 表单流中枚举选项的自定义消息 - C# Bot Framework