溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

C#如何實(shí)現(xiàn)Listbox自繪功能

發(fā)布時(shí)間:2021-11-19 10:49:38 來(lái)源:億速云 閱讀:448 作者:小新 欄目:編程語(yǔ)言

小編給大家分享一下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;        }

最終效果:

C#如何實(shí)現(xiàn)Listbox自繪功能

看完了這篇文章,相信你對(duì)“C#如何實(shí)現(xiàn)Listbox自繪功能”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問(wèn)一下細(xì)節(jié)

免責(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)容。

AI