1. 程式人生 > >[C#.net]ListBox對Item進行重繪,設定背景色和前景色

[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 }