如果要對ListBox控件進行自定義繪製(美化),那麼首先必須將ListBox的DrawMode屬性設置爲OwnerDrawVariable或OwnerDrawFixed。ListBox有個ItemHeight屬性,在DrawMode設置爲Normal時,這個屬性是不可設置的,並且其值是根據當前字體進行計算獲得的。只有當DrawMode設置爲OwnerDrawVariable或OwnerDrawFixed時,設置ItemHeight才生效。
屬性
|
說明
|
Normal | 組件的所有元素都由操作系統繪製,並且元素大小都相等。 |
OwnerDrawFixed | 組件的所有元素都是手動繪製的,並且元素大小都相等。 |
OwnerDrawVariable | 組件的所有元素都由手動繪製,元素大小可能不相等。 |
設置完DrawMode屬性之後,通過ListBox的DrawItem事件可以繪製自己想要的個性化控件。先看一下自己繪製的ListBox控件的效果圖:
(這是選中“英語”的效果)
從圖中可以看出,針對不同的行繪製了不同的背景色,選中項的背景色設置爲藍色,並且還繪製了一個邊框。確實比系統繪製的ListBox好看多了。下面我們來看看代碼,也就是DrawItem事件處理方法。
代碼
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
int index = e.Index;//獲取當前要進行繪製的行的序號,從0開始。
Graphics g = e.Graphics;//獲取Graphics對象。
Rectangle bound = e.Bounds;//獲取當前要繪製的行的一個矩形範圍。
string text = listBox1.Items[index].ToString();//獲取當前要繪製的行的顯示文本。
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{//如果當前行爲選中行。
//繪製選中時要顯示的藍色邊框。
g.DrawRectangle(Pens.Blue, bound.Left, bound.Top, bound.Width - 1, bound.Height - 1);
Rectangle rect = new Rectangle(bound.Left 2, bound.Top 2,
bound.Width - 4, bound.Height - 4);
//繪製選中時要顯示的藍色背景。
g.FillRectangle(Brushes.Blue, rect);
//繪製顯示文本。
TextRenderer.DrawText(g, text, this.Font, rect, Color.White,
TextFormatFlags.VerticalCenter | TextFormatFlags.Left);
}
else
{ //GetBrush爲自定義方法,根據當前的行號來選擇Brush進行繪製。
using (Brush brush = GetBrush(e.Index))
{
g.FillRectangle(brush, bound);//繪製背景色。
}
TextRenderer.DrawText(g, text, this.Font, bound, Color.White,
TextFormatFlags.VerticalCenter | TextFormatFlags.Left);
}
}
OwnerDrawVariable
設置DrawMode屬性爲OwnerDrawVariable後,可以任意改變每一行的ItemHeight和ItemWidth。通過ListBox的MeasureItem事件,可以使每一行具有不同的大小。
(奇偶行的行高不同)
private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
{
//偶數行的ItemHeight爲20
if (e.Index % 2 == 0) e.ItemHeight = 20;
//奇數行的ItemHeight爲40
else e.ItemHeight = 40;
}
總結
這裏最重要的是DrawItem事件和MeasureItem事件,以及MeasureItemEventArgs事件數據類和DrawItemEventArgs事件數據類。在System.Windows.Forms命名空間中,具有DrawItem事件的控件有ComboBox、ListBox、ListView、MenuItem、StatusBar、TabControl,具有MeasureItem事件的控件有ComboBox、ListBox、MenuItem。所以,這些控件可以採用和ListBox相同的方法進行自定義繪製。