C#ComboBox OwnerDraw固定的垂直对齐

时间:2019-08-29 14:39:24

标签: c# winforms

我在OwnerDrawFixed中创建了一个组合框。

这是我用来在其中创建元素的代码。我想知道如何使文本居中对齐吗?

从图像中可以看到,我无法对其进行集中对齐。

你能帮我吗?

private void cboFields_DrawItem(object sender, DrawItemEventArgs e)
{
    using (StringFormat fmt = new StringFormat()
    {
        Alignment = StringAlignment.Center,
        LineAlignment = StringAlignment.Center
    })
    {
        if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
        {
            e.Graphics.FillRectangle(SystemBrushes.MenuHighlight, e.Bounds);
            e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(),
                                    e.Font, SystemBrushes.HighlightText, e.Bounds, fmt);
        }
        else
        {
            e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds);
            e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(),
                                    e.Font, SystemBrushes.MenuText, e.Bounds, fmt);
        }
    }

    e.DrawFocusRectangle();

}

enter image description here

1 个答案:

答案 0 :(得分:0)

它与DropDownStyle = DropDownList一起使用。请注意,当必须绘制文本框部分时,将得到一个e.Index == -1。然后从comboBox1.Text获取文本。

e.DrawBackground();自动为选定的和未选定的条目绘制正确的背景颜色。

e.ForeColor自动为选定和未选定的条目返回正确的文本颜色。

private void ComboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    const TextFormatFlags flags =
        TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter;

    e.DrawBackground();

    string text = e.Index >= 0 ? comboBox1.Items[e.Index].ToString() : comboBox1.Text;
    TextRenderer.DrawText(e.Graphics, text, e.Font, e.Bounds, e.ForeColor, flags);

    e.DrawFocusRectangle();
}

TextRenderer可以提供更好的结果,并通过指定标志来简化文本的对齐方式。您还可以组合其他标志。例如。 TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis在文本不适合时在右侧绘制“ ...”。

它不适用于DropDownStyle = DropDown的原因是您可以编辑文本框部分。因此,在编辑过程中只能选择一部分文本,这需要更复杂的绘图逻辑。