我在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();
}

发布于 2019-08-29 23:16:06
它适用于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的原因是您可以编辑文本框部件。因此,在编辑过程中可能只选择文本的一部分,这需要更复杂的绘图逻辑。
https://stackoverflow.com/questions/57712560
复制相似问题