关于在winform中listbox里面显示图片的问题.

在listbox中显示控件,并且是根据图像的大小来定义item的高度.在实际的开发中发现item的itemheight是受限制的.解决的办法就只有重绘.

主要的是两个事件MeasureItem,DrawItem.以及listbox 的属性DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable.

 private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
        {

           //重新设定item的高度的关键代码.
            if (e.Index >= 0 && e.Index < this.listBox1.Items.Count)
            {
                ImageHelp ih = (ImageHelp)this.listBox1.Items[e.Index];
                e.ItemHeight= ih.img.Height;
            }
        }
        private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
        {

            //绘制图片到item中.
            Graphics g = e.Graphics;

            // draw background, which indicates if object is selected
            e.DrawBackground();

            if (e.Index >= 0 && e.Index < this.listBox1.Items.Count)
            {
                // each item in the list IPainter
                IPainter painter = new ColorPainter(Color.White);

                ImageHelp ih = (ImageHelp)this.listBox1.Items[e.Index];

                // get brush from painter
                Brush brush = painter.PaintBrush;

                // fill the item with painters brush
             
                g.FillRectangle(brush, e.Bounds);
                g.DrawLine(Pens.Black, e.Bounds.X, e.Bounds.Bottom - 1, e.Bounds.Right, e.Bounds.Bottom - 1);

                // draw box with painter name
                string name = ih.name;
                int width = (int)g.MeasureString(name, this.listBox1.Font).Width;

                g.FillRectangle((e.State & DrawItemState.Selected) == DrawItemState.Selected ? Brushes.Yellow : Brushes.White, 3, e.Bounds.Top, width + 3, this.listBox1.Font.Height);

               // g.DrawRectangle(Pens.Black, 3, e.Bounds.Top + 3, width + 3, this.listBox1.Font.Height );
                g.DrawString(name, Font, Brushes.Black, 5, e.Bounds.Top);

                Rectangle photoRct = new Rectangle(
                e.Bounds.X+40,
                e.Bounds.Y,
                ih.img.Width,
                 ih.img.Height);
                e.Graphics.DrawImage(ih.img, photoRct);
                brush.Dispose();
            }
        }

程序运行图片. 

文件下载https://files.cnblogs.com/cookieswolf/listboxEx.zip

posted @ 2008-05-24 13:53  傅红雪  阅读(4069)  评论(2编辑  收藏  举报