回答链接:(Can I put a horizontal line in a combo box or list control?)
我已经在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的建议进行操作,也可以创建将事件处理程序附加到组合框的函数.
void AttachHandler(ComboBox combo) {
combo.DrawMode = DrawMode.OwnerDrawFixed;
combo.DrawItem += new DrawItemEventHandler(cmb_Type_DrawItem);
}
然后,在表单构造函数中,您只需使用:
public Form1() {
AttachHandler(comboBox1);
AttachHandler(comboBox2);
}