C#中ListBox控件设置Item字体并居中显示
2014-11-27 11:08
537 查看
最近项目中又需要客制化一些控件,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);
}
首先将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);
}
相关文章推荐
- C#设置子窗体在主窗体中居中显示解决方案
- c#设置窗体在显示器居中显示
- c# 设置窗体初始化为居中显示
- ios 开发中,如何设置 uitabbar 里面 tabbaritem 不显示文字,只显示图片,图片垂直居中?
- C#设置DataGridView某一具体单元格的内容居中显示
- C#怎么设置子窗体在主窗体中居中显示
- 接下来将介绍C#如何设置子窗体在主窗体中居中显示,本文提供详细的操作步骤,需要的朋友可以参考下
- C#怎么设置子窗体在主窗体中居中显示
- C#dataGridView字体显示设置
- C#-设置窗体在显示器居中显示
- C#dataGridView字体显示设置
- 如何使tabcontrol选项卡上的字体设置为竖着显示(c#,VS2005,winform)
- C#怎么设置子窗体在主窗体中居中显示
- c#设置窗体在显示器居中显示
- C#设置DataGridView控件的标题行的高度并且居中显示
- 将dev-c++中字体和高亮显示设置为vc6.0默认
- Flex中如何利用firstVisibleItem属性,设置或取得第一个显示节点
- ArcIMS设置图层显示(ADF+C#)
- c# asp.net 调用系统设置字体文本框,设置label或页面字体,大小,FontDialog