您好,登錄后才能下訂單哦!
小編給大家分享一下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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。