如何在ListBox中包含图标?

问题描述 投票:1回答:4

我知道之前已经在这里提出了类似的问题,但它们都导致same codeproject article不起作用。有人知道带有图标的工作ListBox吗?

c# .net winforms c#-4.0
4个回答
3
投票

ListView会为你工作吗?这就是我使用的。更容易,你可以让它看起来像一个ListBox。此外,有关MSDN的大量文档可以开始使用。

如何:显示Windows窗体ListView控件的图标 Windows窗体ListView控件可以显示三个图像列表中的图标。 List,Details和SmallIcon视图显示SmallImageList属性中指定的图像列表中的图像。 LargeIcon视图显示LargeImageList属性中指定的图像列表中的图像。列表视图还可以显示另一组图标,这些图标在StateImageList属性中设置,位于大图标或小图标旁边。有关图像列表的详细信息,请参阅ImageList组件(Windows窗体)和如何:使用Windows窗体ImageList组件添加或删除图像。

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


1
投票

如果您在WinForms中工作,那么您必须拥有自己的项目。

请参阅DrawItem event的示例。


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

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


1
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.