2012-01-12 16 views
6

我想繪製的項目,其結尾是一個*字符紅色(並刪除*字符),並繪製其他項目的黑色。Listbox手冊DrawItem大字號

這是我的代碼:

private void listBox1_DrawItem(object sender, DrawItemEventArgs e) 
    { 
     e.DrawBackground() ; //Draw our regular background 
     if (Microsoft.VisualBasic.Strings.Right(listBox1.Items[e.Index].ToString(), 1) == "*") 
     { 
      e.Graphics.DrawString(Microsoft.VisualBasic.Strings.Mid(listBox1.Items[e.Index].ToString(),1,listBox1.Items[e.Index].ToString().Length - 1), e.Font, Brushes.Red, e.Bounds); //Draw the item text in red! 
     } 
     else 
     { 
      e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds); //Draw the item text in its regular color 
     } 
    } 

而且ListBox的DrawMode屬性設置爲OwnerDrawVariable

當listbox的字體是默認字體時,我的代碼工作正常。

但是,當我將字體大小從8.25(默認大小)更改爲14時,一半的文本會在列表框中繪製。像這樣: My listbox when size is 14!

但是,使用默認的字體大小,一切都是正確的。

什麼問題?

回答

6

你必須處理MeasureItem事件,並設置項目有高度:

private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e) 
{ 
    e.ItemHeight = listBox1.Font.Height; 
} 
+2

我用'e.ItemHeight = listBox1.Font.Height;'和它工作得很好。謝謝! – 2012-01-12 13:16:21

+2

非常好,我會用你的評論更新我的回答,所以它不依賴於額外的自定義'ListBoxFontItem'類。 – 2012-01-12 13:18:14