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

C# 如何在列表框中包含图标?,c#,.net,winforms,c#-4.0,C#,.net,Winforms,C# 4.0,我知道以前也有人问过类似的问题,但这些问题都会导致不起作用的结果。有人知道有一个带图标的列表框吗?如果你一直在WinForms中工作,那么你必须自己绘制项目 请参见示例。列表视图是否适合您?这就是我用的。更简单,您可以使它看起来像一个列表框。此外,还有大量有关MSDN的文档可供使用 如何:显示Windows窗体ListView控件的图标 Windows窗体ListView控件可以显示来自三个图像的图标 名单。列表、详细信息和小图标视图显示 SmallImageList属性中指定的图像列表。拉盖孔

我知道以前也有人问过类似的问题,但这些问题都会导致不起作用的结果。有人知道有一个带图标的列表框吗?

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


请参见示例。

列表视图是否适合您?这就是我用的。更简单,您可以使它看起来像一个
列表框
。此外,还有大量有关MSDN的文档可供使用

如何:显示Windows窗体ListView控件的图标
Windows窗体ListView控件可以显示来自三个图像的图标 名单。列表、详细信息和小图标视图显示 SmallImageList属性中指定的图像列表。拉盖孔酒店 视图显示中指定的图像列表中的图像 LargeImageList属性。列表视图还可以显示其他列表 图标集,在StateImageList属性中设置,位于大图标或 小图标。有关图像列表的更多信息,请参见图像列表 组件(Windows窗体)以及如何使用添加或删除图像 Windows窗体ImageList组件


插入方法稍有不同-不要使用列表框。 我没有使用将我限制在其有限的属性和方法集合中的控件,而是创建了自己的列表框

这并不像听起来那么难:

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

上面的代码示例未经测试,但使用了描述的方法,发现非常方便和简单

如果不想将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();
    }

您可以使用矩形设置图标右侧的位置

您应该添加指向该CodeProject文章的链接,并提及与该CodeProject文章不兼容的内容。