您好,登錄后才能下訂單哦!
小編給大家分享一下C#如何實(shí)現(xiàn)Listbox自繪功能,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
使用控件的DrawMode屬性來(lái)實(shí)現(xiàn)控件的自繪,首先將C# Listbox的DrawMode設(shè)置為OwnerDrawVariable,然后實(shí)現(xiàn)DrawItem ,MeasuerItem方法。
編寫(xiě)如下代碼:
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; }
最終效果:
看完了這篇文章,相信你對(duì)“C#如何實(shí)現(xiàn)Listbox自繪功能”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。