【发布时间】:2016-09-16 13:30:59
【问题描述】:
我在 Windows 窗体应用程序中有一个 ComboBox,其中需要显示的项目如下图所示。我只需要第一个分组的固体分隔符。其他项目可以只显示没有分组标题。使用ComboBox 可以根据要求实现,或者我是否必须尝试任何第 3 方控件。任何有价值的建议都会有所帮助。
【问题讨论】:
我在 Windows 窗体应用程序中有一个 ComboBox,其中需要显示的项目如下图所示。我只需要第一个分组的固体分隔符。其他项目可以只显示没有分组标题。使用ComboBox 可以根据要求实现,或者我是否必须尝试任何第 3 方控件。任何有价值的建议都会有所帮助。
【问题讨论】:
您可以通过将DrawMode 设置为OwnerDrawFixed 并处理DrawItem 事件来自己处理ComboBox 的绘图项。然后您可以在您想要的项目下绘制该分隔符:
private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
var comboBox = sender as ComboBox;
var txt = "";
if (e.Index > -1)
txt = comboBox.GetItemText(comboBox.Items[e.Index]);
e.DrawBackground();
TextRenderer.DrawText(e.Graphics, txt, comboBox.Font, e.Bounds, e.ForeColor,
TextFormatFlags.VerticalCenter | TextFormatFlags.Left);
if (e.Index == 2 && !e.State.HasFlag(DrawItemState.ComboBoxEdit)) //Index of separator
e.Graphics.DrawLine(Pens.Red, e.Bounds.Left, e.Bounds.Bottom - 1,
e.Bounds.Right, e.Bounds.Bottom - 1);
}
这部分代码e.State.HasFlag(DrawItemState.ComboBoxEdit)是为了防止在控件的编辑部分绘制分隔符。
注意
ComboBox,您可以查看 Brad Smith 的 A ComboBox Control with Grouping。 (Alternate link.)【讨论】: