在使用.net进行Winform开发时,使用其中的ListBox控件,发现要更改其ItemHeight并不是很容易。但最终还是有方法的,并且可以让文字位于每一项的中间。
设置ListBox的“DrawMode”属性为“OwnerDrawFixed”后,就可以修改其ItemHeight了。
此时我们要重载ListBox的“DrawItem”事件,才能在其中显示出Item,具体代码如下:
private void lstUnPrivilege_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
e.DrawFocusRectangle();
SYSPrivilege p = lstUnPrivilege.Items[e.Index] as SYSPrivilege;
//让文字位于Item的中间
float difH = (e.Bounds.Height - e.Font.Height) / 2;
RectangleF rf = new RectangleF(e.Bounds.X, e.Bounds.Y + difH, e.Bounds.Width, e.Font.Height);
e.Graphics.DrawString(p.PrivilegeName, e.Font, new SolidBrush(e.ForeColor), rf);
}