2016-09-16 98 views
1

我在Windows窗体应用程序中有一个ComboBox,其中项目需要显示,如下图所示。我只需要第一个分组的固体分隔符。其他项目可以不显示分组头。使用ComboBox它可以按照要求来实现,或者我必须尝试任何第三方控件。任何有价值的建议都会有帮助。在Windows窗体应用程序中分组组合框项目

enter image description here

回答

2

您可以处理通过设置其DrawModeOwnerDrawFixed和处理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)这部分是为了防止在控件的编辑部分绘制分隔符。

enter image description here

注意

  • 答案满足您要求的问题的要求。但是一些用户可能希望用组文本对项目进行分组,而不仅仅是分隔符。要查看支持这些组文本的ComboBox,您可以查看Brad Smith的 A ComboBox Control with Groupig
相关问题