如何在列表框中包含图标?

本文关键字:包含 图标 列表 | 更新日期: 2023-09-27 18:16:11

我知道以前已经有人问过类似的问题,但它们都导致同一篇代码项目文章不起作用。有人知道有图标的列表框吗?

如何在列表框中包含图标?

ListView是否适合您?这就是我用的。更简单,你可以让它看起来像一个ListBox。此外,MSDN上有大量的文档可供入门。

如何显示Windows窗体ListView控件的图标
Windows Forms ListView控件可以显示三个图像中的图标列表。列表、细节和SmallIcon视图显示来自在smallagelist属性中指定的图像列表。的LargeIcon属性中指定的图像列表中的图像LargeImageList财产。列表视图还可以显示附加的一组图标,设置在statimagelist属性中,在大的或旁边小图标。有关映像列表的更多信息,请参见ImageList组件(Windows窗体)和如何:添加或删除图像Windows Forms ImageList组件。

从如何:显示Windows窗体的图标列表控件

插入

如果你不想将ListBox更改为ListView,你可以为drawwitemevent编写一个处理程序。例如:

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

你可以通过矩形来设置图标的位置

如果你在WinForms中工作,那么你必须自己绘制你的项目。

一个稍微不同的方法——不要使用列表框。而不是使用控件,将我限制在其有限的属性和方法集,我做了一个我自己的列表框。

这并不像听起来那么难:

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;      
}
上面的代码样本没有经过测试,但使用了所描述的方法,发现非常方便和简单。