动态列表框,每个列表框都有 DrawItem 事件

Dynamic List Boxes with DrawItem event for each one of them

我正在创建一个 TabControl,它在每个动态创建的 TabPage 上都包含一个动态创建的 ListBox,每个列表框都有不同的内容。 对于每个 ListBox,我想处理里面的文本(根据显示代码中不可见的状态更改它的颜色)。

目前,我正在使用 class 为特定 ListBox 的文本着色,该 class 保存文本的颜色和将用于一行的消息。

用于手动创建的列表框的代码示例:

    private void listBoxLogs_DrawItem(object sender, DrawItemEventArgs e)
    {
        if (e.Index < 0)
        {
            return;
        }

        ListBoxLogsItem item = listBoxLogs.Items[e.Index] as ListBoxLogsItem;
        if (item != null)
        {
            e.DrawBackground();

            e.Graphics.DrawString(item.m_message, listBoxLogs.Font, item.m_color, e.Bounds, System.Drawing.StringFormat.GenericDefault);

            System.Drawing.Graphics g = listBoxLogs.CreateGraphics();
            System.Drawing.SizeF s = g.MeasureString(item.m_message, listBoxLogs.Font);

            if (s.Width > listBoxLogs.HorizontalExtent)
            {
                listBoxLogs.HorizontalExtent = (int)s.Width + 2;
            }
        }
    }

以下代码用于创建 TabPage 和 ListBox:

    // _tagName is an identifier used to know the TabPage and ListBox in which the text will be added
    private void AddTabPage(string _tagName)
    {
        ListBox listBox = new ListBox();
        listBox.Text = _tagName;
        listBox.Name = _tagName;
        listBox.Location = new System.Drawing.Point(6, 6);
        listBox.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
        listBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBoxLogs_DrawItem);
        listBox.Size = new System.Drawing.Size(628, 378);
        listBox.FormattingEnabled = true;
        listBox.HorizontalScrollbar = true;
        listBox.ItemHeight = 17;
        listBox.TabIndex = 15;

        // TODO: Remove this line. Added just for testing
        listBox.Items.Add(new ListBoxLogsItem(System.Drawing.Brushes.Black, ""));

        TabPage tab = new TabPage();
        tab.Name = _tagName;
        tab.Controls.Add(listBox);

        // Add the TabPage to the TabControl only when it's available
        ExecuteOnControlThread(delegate
        {
            tabControl.Controls.Add(tab);
        });
    }

我不知道如何识别调用 DrawItemEventHandler 的 ListBox "this.listBoxLogs_DrawItem"。

有人可以告诉我如何做到这一点,或者可以让我获得相同结果的不同方法吗?

sender 是引发您正在处理的事件的控件。当您在属性网格中创建处理程序时,选择的控件是什么?列表框。这就是引发事件的控件。

private void listBoxLogs_DrawItem(object sender, DrawItemEventArgs e)
{
    ListBox lbSender = (ListBox)sender;

    // ...other stuff
}

一般情况下,在处理程序方法中设置一个断点,并在引发事件时在运行时检查参数。这始终是让您了解这些事情的快速方法。