将水平线放在combobox中或列出C#中的控件

回答链接:( 我可以在combobox或列表控件中放置水平线吗? )

我在C#(VS 2010)Windows窗体中创建了一个代码,但它需要改进。 项目前面的符号“ – ”会在项目后面显示一条线。

我在组合项集合中的输入如下:

-All Names Henry (Father) -Nancy (Mother) Sapphire Vincent 

我的组合显示如下:

 All Names ------------------ Henry (Father) Nancy (Mother) ------------------ Sapphire Vincent 

虽然我的代码是:

  public Form1() { InitializeComponent(); comboBox1.DrawMode = DrawMode.OwnerDrawFixed; comboBox1.DrawItem += new DrawItemEventHandler(cmb_Type_DrawItem); } void cmb_Type_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); string a = comboBox1.Items[e.Index].ToString(); if (comboBox1.Items[e.Index].ToString().Substring(0, 1) == "-") { e.Graphics.DrawLine(Pens.Black, new Point(e.Bounds.Left, e.Bounds.Bottom - 1), new Point(e.Bounds.Right, e.Bounds.Bottom - 1)); a = a.Substring(1, a.Length - 1); } TextRenderer.DrawText(e.Graphics, a, comboBox1.Font, e.Bounds, comboBox1.ForeColor, TextFormatFlags.Left); e.DrawFocusRectangle(); } 

我需要的改进是在“cmb_Type_DrawItem”中我希望“comboBox1”被参数化,所以当我调用它时可以应用于任何调用它的comboBox(不仅仅是comboBox1)。

你可以像Blau建议的那样去做,也可以创建一个将事件处理程序附加到combobox的函数。

 void AttachHandler(ComboBox combo) { combo.DrawMode = DrawMode.OwnerDrawFixed; combo.DrawItem += new DrawItemEventHandler(cmb_Type_DrawItem); } 

然后,在表单构造函数中,您只需使用:

 public Form1() { AttachHandler(comboBox1); AttachHandler(comboBox2); } 

创建自己的combobox:

  public class MyComboBox : ComboBox { override DrawItem() { .... } } 

使用Martin的解决方案加上一个公共变量。

  public Form1() { InitializeComponent(); AttachHandler(comboBox1); AttachHandler(comboBox2); AttachHandler(comboBox3); AttachHandler(comboBox4); AttachHandler(comboBox5); } void AttachHandler(ComboBox combo) { combo.DrawMode = DrawMode.OwnerDrawFixed; combo.DrawItem += new DrawItemEventHandler(cmb_Type_DrawItem); } //using mycombo to make combobox variable void cmb_Type_DrawItem(object sender, DrawItemEventArgs e) { var mycombo = (ComboBox) sender; // This is what I meant e.DrawBackground(); string a = mycombo.Items[e.Index].ToString(); if (mycombo.Items[e.Index].ToString().Substring(0, 1) == "-") { e.Graphics.DrawLine(Pens.Black, new Point(e.Bounds.Left, e.Bounds.Bottom - 1), new Point(e.Bounds.Right, e.Bounds.Bottom - 1)); a = a.Substring(1, a.Length - 1); } TextRenderer.DrawText(e.Graphics, a, mycombo.Font, e.Bounds, mycombo.ForeColor, TextFormatFlags.Left); e.DrawFocusRectangle(); }