最近项目中又需要客制化一些控件,draw来draw去真的好烦,其中有ListBox客制化并居中显示字体,特记录下供各位以备不时,比较简单,禁止拍砖哈~~~
首先将Listbox的DrawMode属性设置为DrawMode.OwnerDrawVariable
加载事件DrawItem和MeasureItem,如不加入MeasureItem事件,则Item会使用默认高度重绘,字体显示不完全,各位可以自己尝试一下
ListBox _listBox = new ListBox();
_listBox.DrawMode = DrawMode.OwnerDrawVariable;
_listBox.DrawItem += _listBox_DrawItem;
_listBox.MeasureItem += _listBox_MeasureItem;
// set listbox item height
void _listBox_MeasureItem(object sender, MeasureItemEventArgs e)
{
e.ItemHeight = 30;
}
// make the item text center aligned
void _listBox_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();