用于检测添加到ComboBox的项目的事件

我正在创建一个inheritance自ComboBox的自定义控件。 我需要检测何时将一个Item添加到ComboBox以执行我自己的检查。 它是C#还是Vb.NET并不重要,但我不知道该怎么做。

我尝试了我在互联网上找到的所有东西,包括这个post ,但答案中的链接是离线的,我没想到我应该怎么做。

例如,Vb.net中的此代码:

Public Sub SomeFunc() Handles Items.CollectionChanged '.... End Sub 

它表示Items属性未定义WithEvents

该控件未使用BindingSource。 我需要控件在添加项目时执行自定义操作。 项目直接添加到.Items属性中:

 customComboBox.Items.Add("item"); 

可以吗?

我认为最好的方法是监听本机ComboBox消息 :

  • CB_ADDSTRING
  • CB_INSERTSTRING
  • CB_DELETESTRING
  • CB_RESETCONTENT

不要被STRING这个词所迷惑,每当你添加,插入或删除一个项目时都会被解雇。 所以当清单清除时。

 Public Class UIComboBox Inherits ComboBox Private Sub NotifyAdded(index As Integer) End Sub Private Sub NotifyCleared() End Sub Private Sub NotifyInserted(index As Integer) End Sub Private Sub NotifyRemoved(index As Integer) End Sub Protected Overrides Sub WndProc(ByRef m As Message) Select Case m.Msg Case CB_ADDSTRING MyBase.WndProc(m) Dim index As Integer = (Me.Items.Count - 1) Me.NotifyAdded(index) Exit Select Case CB_DELETESTRING MyBase.WndProc(m) Dim index As Integer = m.WParam.ToInt32() Me.NotifyRemoved(index) Exit Select Case CB_INSERTSTRING MyBase.WndProc(m) Dim index As Integer = m.WParam.ToInt32() Me.NotifyAdded(If((index > -1), index, (Me.Items.Count - 1))) Exit Select Case CB_RESETCONTENT MyBase.WndProc(m) Me.NotifyCleared() Exit Select Case Else MyBase.WndProc(m) Exit Select End Select End Sub Private Const CB_ADDSTRING As Integer = &H143 Private Const CB_DELETESTRING As Integer = &H144 Private Const CB_INSERTSTRING As Integer = 330 Private Const CB_RESETCONTENT As Integer = &H14B End Class 

如果您的ComboBoxBindingSource支持,那么您可以侦听AddingItem事件并相应地处理它。

您可以控制何时将项目添加到ComboBox。 因此,当发生这种情况时,没有事件被触发。

您是向ComboBox添加项目的人。 执行此操作不是外部可执行文件,而是您的代码。 因此,您可以确保所有添加都是通过函数AddItem(item As Object){…}来完成的,您应该处理在项目中添加项目时需要执行的逻辑。 所以,不需要事件。