Listbox手册DrawItem大字体大小

Mah*_*asi 10 c# listbox winforms

我正在尝试绘制其末尾为*红色字符(并删除该*字符)并以黑色绘制其他项目的项目.

这是我的代码:

    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
        }
    }
Run Code Online (Sandbox Code Playgroud)

同时DrawMode列表框的属性设置为OwnerDrawVariable.

当listbox的字体是默认字体时,我的代码工作正常.

但是当我将字体大小从8.25(默认大小)更改为14时,文本的一半将在列表框中绘制.像这样: 我的列表框大小为14!

但是使用默认字体大小,一切都是正确的.

问题是什么?

Fré*_*idi 9

您必须处理MeasureItem事件并设置项目的高度:

private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
{
     e.ItemHeight = listBox1.Font.Height;
}
Run Code Online (Sandbox Code Playgroud)

  • 我使用了`e.ItemHeight = listBox1.Font.Height;`它运行良好.谢谢! (3认同)
  • 很好,我会用你的评论更新我的答案,所以它不依赖于一个额外的自定义`ListBoxFontItem`类. (2认同)