C#中ListBox控制元件設定Item字型並居中顯示
最近專案中又需要客製化一些控制元件,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();
e.DrawFocusRectangle();
System.Drawing.StringFormat strFmt = new System.Drawing.StringFormat(System.Drawing.StringFormatFlags.NoClip);
strFmt.Alignment = System.Drawing.StringAlignment.Center;
RectangleF rf = new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height);
//You can also use DrawImage to add some customized image before or after text string, of course backgroud image
e.Graphics.DrawString(this.Items[e.Index].ToString(), e.Font, new System.Drawing.SolidBrush(e.ForeColor), rf, strFmt);
}