温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

ListBox控件的项如何设置不同的对齐方式

发布时间:2024-08-08 09:18:03 来源:亿速云 阅读:87 作者:小樊 栏目:编程语言

可以通过设置ListBox控件的Style属性来改变项的对齐方式。可以使用以下代码来设置ListBox控件的项为左对齐、居中或右对齐:

listBox1.DrawMode = DrawMode.OwnerDrawFixed;

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    if (e.Index >= 0)
    {
        StringFormat format = new StringFormat();
        format.LineAlignment = StringAlignment.Center;
        
        // 左对齐
        format.Alignment = StringAlignment.Near;
        e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds, format);

        // 居中
        format.Alignment = StringAlignment.Center;
        e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds, format);

        // 右对齐
        format.Alignment = StringAlignment.Far;
        e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds, format);
    }
}

以上代码将ListBox控件的DrawMode属性设置为OwnerDrawFixed,并在ListBox的DrawItem事件处理程序中自定义绘制ListBox的项,通过设置不同的StringAlignment属性来实现左对齐、居中和右对齐。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI