[C#.net]ListBox對Item進行重繪,設置背景色和前景色


別的不多說了,上代碼,直接看

首先設置這行,或者屬性窗口設置,這樣才可以啟動手動繪制,參數有三個

Normal: 自動繪制

OwnerDrawFixed:手動繪制,但間距相同

OwnerDrawVariable:手動繪制,間距不同

listBox1.DrawMode= DrawMode.OwnerDrawFixed

然后在DrawItem事件中寫繪制代碼

            e.Graphics.FillRectangle(new SolidBrush(color), e.Bounds);//繪制背景
            e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds);//繪制文字
            e.DrawFocusRectangle();//繪制聚焦框

 其中繪制聚焦框沒啥效果,貌似需要是ComboBox僅在DropDownStyle=DropDownList時有效

如果設置為了OwnerDrawVariable,則還需要設置MeasureItem事件,用於返回每行的高度(e.ItemWidth = 260)。

如果是繪制虛線,則pen需要設置DashStyle或者DashPattern(優先級高)。

 1         private void lstLog_DrawItem(object sender, DrawItemEventArgs e)
 2         {
 3             if (e.Index >= 0)
 4             {
 5                 e.DrawBackground();
 6                 Brush myBrush = Brushes.Black; //前景色
 7                 Color bgColor = Color.White;   //背景色
 8                 if(lstLog.Items[e.Index].ToString().Contains("成功"))
 9                 {
10                     bgColor = Color.RoyalBlue;
11                 }
12                 if (lstLog.Items[e.Index].ToString().Contains("失敗"))
13                 {
14                     bgColor = Color.Magenta;
15                 }
16                 //繪制背景
17                 e.Graphics.FillRectangle(new SolidBrush(bgColor), e.Bounds);
18                 //繪制文字
19                 e.Graphics.DrawString(lstLog.Items[e.Index].ToString(), e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
20                 //繪制聚焦框
21                 e.DrawFocusRectangle();
22             }
23         }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM