首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# ComboBox OwnerDrawFixed垂直对齐

C# ComboBox OwnerDrawFixed垂直对齐
EN

Stack Overflow用户
提问于 2019-08-29 22:39:24
回答 1查看 70关注 0票数 0

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

这是我用来在里面创建元素的代码。我想知道怎样才能使文本居中对齐?

正如你从图像中看到的,我不能居中对齐它。

你能帮帮我吗?

代码语言:javascript
复制
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();

}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-29 23:16:06

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

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

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

代码语言:javascript
复制
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的原因是您可以编辑文本框部件。因此,在编辑过程中可能只选择文本的一部分,这需要更复杂的绘图逻辑。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57712560

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档