使用控件的DrawMode属性来实现控件的自绘,首先将C# Listbox的DrawMode设置为OwnerDrawVariable,然后实现DrawItem ,MeasuerItem方法。
编写如下代码:
- private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
- {
- e.DrawBackground();
- Rectangle r = new Rectangle(0, 0, lbCustomDraw.Width, 100);
- bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);
- LinearGradientBrush lgb = null;
- if (!selected)
- {
- lgb = new LinearGradientBrush(r, Color.Red, Color.Yellow, LinearGradientMode.Horizontal);
- }
- else
- {
- lgb = new LinearGradientBrush(r, Color.Cyan, Color.White, LinearGradientMode.Horizontal);
- }
- e.Graphics.FillRectangle(lgb, e.Bounds);
- e.Graphics.DrawRectangle(SystemPens.WindowText, e.Bounds);
- Rectangle r2 = e.Bounds;
- string displayText = (string)lbCustomDraw.Items[e.Index];
- SizeF size = e.Graphics.MeasureString(displayText, this.Font);
- r2.Y = (int)(r2.Height / 2) - (int)(size.Height / 2) + e.Bounds.Y;
- r2.X = 2;
- e.Graphics.DrawString(displayText, this.Font, Brushes.Black, r2);
- e.DrawFocusRectangle();
- }
- private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
- {
- string displayText = (string)lbCustomDraw.Items[e.Index];
- SizeF size = e.Graphics.MeasureString(displayText, this.Font);
- size.Height += 10;
- e.ItemHeight = (int)size.Height;
- }
最终效果:
多彩世界 实现C# Listbox自绘
以上就是C# Listbox的自绘方法,很漂亮吧。
【编辑推荐】