我创建了一个TabControl,其中包含每个动态创建的TabPage动态创建的列表框,每个列表框都有不同的内容。 对于每个ListBox,我想要处理里面的文本(根据显示的代码中不可见的状态更改它的颜色)。其中包含DrawItem事件动态列表框
目前,我正在通过使用保存文本颜色和将用于行的消息的类来为特定ListBox着色。
实施例与用于手动创建的列表框的代码:
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和列表框:
// _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“this.listBoxLogs_DrawItem”的ListBox。
有人可以告诉我我该怎么做,或者让我得到相同结果的另一种方式?
我不确定你在问什么,但你可以通过引用来标识它们,或者设置ListBox.Name。你能告诉你想用哪种方式识别他们吗?传递的参数'sender'是你的ListBox。只需将它投入ListBoxàla 'var anyListBox =(ListBox)sender;' – Bagerfahrer
谢谢@Bagerfahrer 这就是我错过的东西。 – Flavius