【问题标题】:Grouping ComboBox Items in Windows Forms Application在 Windows 窗体应用程序中对 ComboBox 项进行分组
【发布时间】:2016-09-16 13:30:59
【问题描述】:

我在 Windows 窗体应用程序中有一个 ComboBox,其中需要显示的项目如下图所示。我只需要第一个分组的固体分隔符。其他项目可以只显示没有分组标题。使用ComboBox 可以根据要求实现,或者我是否必须尝试任何第 3 方控件。任何有价值的建议都会有所帮助。

【问题讨论】:

    标签: c# .net winforms combobox


    【解决方案1】:

    您可以通过将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.)

    【讨论】:

      猜你喜欢
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-09
      • 1970-01-01
      • 1970-01-01
      • 2012-06-12
      • 1970-01-01
      相关资源
      最近更新 更多