2017-10-18 150 views
0

我创建了一个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。

有人可以告诉我我该怎么做,或者让我得到相同结果的另一种方式?

+0

我不确定你在问什么,但你可以通过引用来标识它们,或者设置ListBox.Name。你能告诉你想用哪种方式识别他们吗?传递的参数'sender'是你的ListBox。只需将它投入ListBoxàla 'var anyListBox =(ListBox)sender;' – Bagerfahrer

+0

谢谢@Bagerfahrer 这就是我错过的东西。 – Flavius

回答

2

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

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

    // ...other stuff 
} 

通常,在处理程序方法中插入断点并在引发事件时检查运行时的参数。这总是一个快速的方式来让你的方向与这些事情。

+1

谢谢@Ed 我不知道为什么我没有查看发件人......我已经看到它在Watch中显示的值是{SelectedItem =“”},并没有想到看起来会发毛。 – Flavius