C#中ListBox控件设置Item字体并居中显示

本文介绍如何通过设置ListBox的DrawMode为OwnerDrawVariable,并处理DrawItem和MeasureItem事件,来实现ListBox中字体的居中显示。通过MeasureItem事件设置Item的高度,确保字体完整显示,然后在DrawItem事件中利用StringFormat进行文字居中对齐,从而达到理想的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值