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 に答える