19

C# 简而言之,我可以在列表框中显示图像吗?我有一个用户列表,我想在某些名称旁边显示一个绿色勾号,这可能吗?

谢谢

4

3 回答 3

30

以下代码显示如何在列表框中进行自定义绘图。

using System.Windows.Forms;
using System.Drawing;

namespace Toolset.Controls
{
    public class CustomDrawListBox : ListBox
    {
        public CustomDrawListBox()
        {
            this.DrawMode = DrawMode.OwnerDrawVariable; // We're using custom drawing.
            this.ItemHeight = 40; // Set the item height to 40.
        }

        protected override void OnDrawItem(DrawItemEventArgs e)
        {
            // Make sure we're not trying to draw something that isn't there.
            if (e.Index >= this.Items.Count || e.Index <= -1)
                return;

            // Get the item object.
            object item = this.Items[e.Index];
            if (item == null)
                return;

            // Draw the background color depending on 
            // if the item is selected or not.
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            {
                // The item is selected.
                // We want a blue background color.
                e.Graphics.FillRectangle(new SolidBrush(Color.Blue), e.Bounds);
            }
            else
            {
                // The item is NOT selected.
                // We want a white background color.
                e.Graphics.FillRectangle(new SolidBrush(Color.White), e.Bounds);
            }

            // Draw the item.
            string text = item.ToString();
            SizeF stringSize = e.Graphics.MeasureString(text, this.Font);
            e.Graphics.DrawString(text, this.Font, new SolidBrush(Color.White),
                new PointF(5, e.Bounds.Y + (e.Bounds.Height - stringSize.Height) / 2));
        }
    }
}
于 2009-01-23T15:52:55.137 回答
2

System.Windows.Forms.ListView 将很容易做到这一点。但是,如果您希望列表处于“详细信息”视图中,则可能需要比 ListBox 更努力地工作。

于 2009-01-23T15:39:44.837 回答
0

在 WPF 中这很简单,但如果您使用的是 winforms,则无法使用 System.Windows.Forms.ListBox 控件来完成。您可以使用 ListView 控件或第三方控件来执行此操作。

于 2009-01-23T13:51:44.540 回答