C# 在所有者绘制模式下如何将列表框项目中的文本居中

C# 在所有者绘制模式下如何将列表框项目中的文本居中,c#,winforms,listboxitems,C#,Winforms,Listboxitems,我想对列表框项目进行一些视觉更改,因此我将DrawMode设置为“OwnerDrawFixed” 我希望文本位于项目的中间 垂直地,这样做很容易: private void listTypes_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); e.Graphics.DrawString(listTypes.Items[e.Index].ToString(), e.Fon

我想对列表框项目进行一些视觉更改,因此我将DrawMode设置为“OwnerDrawFixed” 我希望文本位于项目的中间 垂直地,这样做很容易:

private void listTypes_DrawItem(object sender, DrawItemEventArgs e)
{
   e.DrawBackground();
   e.Graphics.DrawString(listTypes.Items[e.Index].ToString(),
                e.Font, Brushes.Black, e.Bounds.Left, e.Bounds.Top + e.Bounds.Height/4
                , StringFormat.GenericDefault);  
   e.DrawFocusRectangle();  
}
但是要使文本水平居中,我需要知道文本宽度 如何获得它,或者是否有更好的方法来实现这一点

您可以使用代码进行尝试

    void listTypes_DrawItem(object sender, DrawItemEventArgs e)
    {
        ListBox list = (ListBox)sender;
        if (e.Index > -1)
        {
            object item = list.Items[e.Index];
            e.DrawBackground();
            e.DrawFocusRectangle();
            Brush brush = new SolidBrush(e.ForeColor);
            SizeF size = e.Graphics.MeasureString(item.ToString(), e.Font);
            e.Graphics.DrawString(item.ToString(), e.Font, brush, e.Bounds.Left + (e.Bounds.Width / 2 - size.Width / 2), e.Bounds.Top + (e.Bounds.Height / 2 - size.Height / 2)); 
        }
    }

您应该使用TextRenderer.DrawText()使文本外观与表单中其他控件呈现文本的方式一致。它已经有了一个重载,可以接受一个矩形,并将文本置于该矩形的中心。只要通过e.Bounds。您还需要注意项目状态,为所选项目使用不同的颜色。像这样:

    private void listBox1_DrawItem(object sender, DrawItemEventArgs e) {
        e.DrawBackground();
        if (e.Index >= 0) {
            var box = (ListBox)sender;
            var fore = box.ForeColor;
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) fore = SystemColors.HighlightText;
            TextRenderer.DrawText(e.Graphics, box.Items[e.Index].ToString(),
                box.Font, e.Bounds, fore);
        }
        e.DrawFocusRectangle();
    }

谢谢你,先生,也许为那些对C#和WindowsForms不够熟悉的人添加一点解释会很好。