c# - 在 C# 中将水平线放在组合框或列表控件中

标签 c# winforms

回答链接:(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”被参数化,所以当我调用它时,它可以应用于调用它的任何组合框(不仅仅是组合框 1)。

最佳答案

您可以按照 Blau 的建议进行操作,也可以创建一个将事件处理程序附加到组合框的函数。

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

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

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

关于c# - 在 C# 中将水平线放在组合框或列表控件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18092613/

相关文章:

c# - 迁移到早期版本的 C# 时需要考虑哪些因素?

c# - 如何将 XML 数据传递给在 Web 浏览器控件中运行的网页?

c# - 在字符到达文本框之前对其进行修改

winforms - 如何为不懂计算机的人实现 UI?

c# - StringDictionary 类和 Dictionary<String,String> 之间有区别吗

c# - OrderBy 可以为一个元素多次评估委托(delegate)吗?

c# - 按 namespace 对列表进行排序

c# - Windows 窗体中的选项卡式表单导航

c# - 如何在 UserControl 中自动清理 ToolTip

c# - 业务层 (BLL) 数据访问层 (DAL) 和 UI 之间的通用结构?