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时,文本的一半将在列表框中绘制.像这样:

但是使用默认字体大小,一切都是正确的.
问题是什么?
您必须处理MeasureItem事件并设置项目的高度:
private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
{
e.ItemHeight = listBox1.Font.Height;
}
Run Code Online (Sandbox Code Playgroud)