C# 我能在列表框中显示图片吗?

19

在C#中,我能否在列表框中显示图像?我有一个用户列表,我想在一些姓名旁边显示绿色的勾号,这可行吗?

谢谢


你是在使用Winforms还是WPF? - Gerrie Schenck
Steve,这篇文章可能会指引你正确的方向:http://www.codeproject.com/KB/combobox/glistbox.aspx - gkrogers
我想说的是,我强烈建议不要使用那个教程。它非常有 bug,让读者有太多问题,并且编码质量很差。 - dnclem
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));
        }
    }
}

2

System.Windows.Forms.ListView可以轻松解决这个问题。如果您想以“详细”视图的方式呈现列表,则可能需要比ListBox更努力。


0
在WPF中很简单,但如果你使用的是winforms,则无法使用System.Windows.Forms.ListBox控件来实现。你可以使用ListView控件或第三方控件来实现。

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