您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
小编给大家分享一下C#如何实现Listbox自绘功能,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
使用控件的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自绘功能”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。