2012-01-12 33 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