在Windows窗体应用程序中对ComboBox项进行分组

问题描述 投票:1回答:1

我在Windows Forms Application中有一个ComboBox,其中的项目需要显示如下图所示。我只需要第一次分组的固体分隔符。其他项目只能显示没有分组标题。使用ComboBox它可以按照要求实现,或者我必须尝试任何第三方控件。任何有价值的建议都会有所帮助。

enter image description here

c# .net winforms combobox
1个回答
2
投票

您可以通过将ComboBox设置为DrawMode并处理OwnerDrawFixed事件来自己处理DrawItem的绘图项目。然后,您可以在所需的项目下绘制该分隔符:

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)的这部分是为了防止在控件的编辑部分中绘制分隔符。

enter image description here

注意

  • 答案满足您在问题中要求的要求。但是有些用户可能希望使用组文本对项目进行分组,而不仅仅是分隔符。要查看支持此类组文本的ComboBox,您可以查看Brad Smith的 A ComboBox Control with Grouping。 (Alternate link。)
© www.soinside.com 2019 - 2024. All rights reserved.