如何在我的ListBox中添加图标?

3

我知道这里之前已经有类似的问题,但是它们都指向一个不起作用的codeproject文章。有人知道有带图标的工作ListBox吗?


1
你应该在那篇 CodeProject 文章中添加一个链接。 - Nasreddine
2
并提到CodeProject文章中有哪些问题。请仅返回翻译文本。 - slugster
4个回答

5
你需要使用ListView吗?这是我使用的。它更容易使用,而且你可以使它看起来像一个ListBox。此外,在MSDN上有很多文档可以帮助你入门。

如何显示Windows Forms ListView控件的图标
Windows Forms ListView控件可以从三种图像列表中显示图标。列表、详细信息和小图标视图从在SmallImageList属性中指定的图像列表中显示图像。大图标视图从在LargeImageList属性中指定的图像列表中显示图像。列表视图还可以在大型或小型图标旁边显示设置在StateImageList属性中的另一组图标。有关图像列表的详细信息,请参阅ImageList Component (Windows Forms) 和 How to: Add or Remove Images with the Windows Forms ImageList Component。

How to: Display Icons for the Windows Forms ListView Control插入。

3
如果您不想将ListBox更改为ListView,您可以编写一个DrawItemEvent处理程序。例如:
private void InitializeComponent()
{
    ...
    this.listBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBox_DrawItem);
    ...
 }
private void listBox_DrawItem(object sender, DrawItemEventArgs e)
    {
        if (e.Index == -1)
            return;
        // Draw the background of the ListBox control for each item.
        e.DrawBackground();
        var rect = new Rectangle(e.Bounds.X+10, e.Bounds.Y+8, 12, 14);
       //assuming the icon is already added to project resources
        e.Graphics.DrawIconUnstretched(YourProject.Properties.Resources.YouIcon, rect);
        e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(),
            e.Font, Brushes.Black, new Rectangle(e.Bounds.X + 25, e.Bounds.Y + 10, e.Bounds.Width, e.Bounds.Height), StringFormat.GenericDefault);
        // If the ListBox has focus, draw a focus rectangle around the selected item.
        e.DrawFocusRectangle();
    }

您可以通过调整矩形来设置图标的位置。

1
如果你在WinForms中工作遇到了困难,那么你就需要自己绘制你的项目。
请参考DrawItem事件的示例。

1
一个略有不同的方法 - 不使用列表框。 我不想被那个控件所限制,因为它只有有限的属性和方法,所以我自己制作了一个列表框。
这并不像听起来那么难:
int yPos = 0;    
Panel myListBox = new Panel();
foreach (Object object in YourObjectList)
{
    Panel line = new Panel();
    line.Location = new Point(0, Ypos);
    line.Size = new Size(myListBox.Width, 20);
    line.MouseClick += new MouseEventHandler(line_MouseClick);
    myListBox.Controls.Add(line);

    // Add and arrange the controls you want in the line

    yPos += line.Height;
}

myListBox事件处理程序示例 - 选择一行:

private void line_MouseClick(object sender, MouseEventArgs)
{
    foreach (Control control in myListBox.Controls)
        if (control is Panel)
            if (control == sender)
                control.BackColor = Color.DarkBlue;
            else
                control.BackColor = Color.Transparent;      
}

上述代码示例未经过测试,但所描述的方法被使用并发现非常方便和简单。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接