在 C# 中的组合框或列表控件中放置水平线 [英] putting horizontal line in a combo box or list control in C#
本文介绍了在 C# 中的组合框或列表控件中放置水平线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
回答链接:(我可以在组合框或列表控件中放置一条水平线吗?)
我已经在 C# (VS 2010) Windows 窗体中创建了一个代码,但它需要改进.项目前的符号-"在项目后呈现一行.
I've create a code in C# (VS 2010) Windows Forms but it needs improvement. The symbol "-" in front of the item renders a line after the item.
我在组合项集合中的输入如下:
My inputs in the combo item collections are as follow:
-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"进行参数化,因此当我调用它时,它可以应用于任何调用它的组合框(不仅仅是组合框1).
The improvement I need is in the "cmb_Type_DrawItem" i wanted the "comboBox1" to be parametrized so when i call it can be applied to any comboBox that called it (not just comboBox1).
推荐答案
使用 Martin 的解决方案加上一个公共变量.
Using Martin's solution plus a public variable.
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();
}
这篇关于在 C# 中的组合框或列表控件中放置水平线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文