【发布时间】:2017-03-03 00:03:58
【问题描述】:
我正在尝试创建一个包含文本框和标签作为单个项目的菜单列表项。在下面的代码中,我创建了从 ToolStripControlHost 继承的必要的自定义控件类,当在表单菜单中创建时,它的外观和行为符合预期。
我遇到的问题是控件的事件没有触发处理程序例程。在下面的示例中,我期望发生的是,当用户在文本框中键入一条消息时,应该显示一条消息(其他事件也有同样的问题)。
谢谢。
控制类:
Public Class ToolStripTextBoxWithLabel
Inherits ToolStripControlHost
Public Sub New(Optional ByVal lblText As String = "label")
MyBase.New(New ControlPanel(lblText))
End Sub
Public ReadOnly Property ControlPanelControl() As ControlPanel
Get
Return CType(Me.Control, ControlPanel)
End Get
End Property
End Class
Public Class ControlPanel
Inherits Panel
Friend WithEvents txt As New TextBox
Friend WithEvents lbl As New Label
Public Sub New(ByVal lblText As String)
Me.Height = 20
lbl.Anchor = AnchorStyles.Left Or AnchorStyles.Top Or AnchorStyles.Bottom
lbl.Text = lblText
lbl.TextAlign = ContentAlignment.BottomLeft
lbl.AutoSize = True
lbl.Height = Me.Height
lbl.Location = New Point(0, 3)
lbl.Parent = Me
txt.Anchor = AnchorStyles.Left Or AnchorStyles.Right Or AnchorStyles.Top
txt.Location = New Point(lbl.Right + 3, 0)
txt.Width = Me.Width - txt.Left
txt.Parent = Me
End Sub
End Class
表单实现:
Public Class Form1
Friend tb_SearchBox As ToolStripTextBoxWithLabel
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
tb_SearchBox = New ToolStripTextBoxWithLabel("Search:") With {.Name = "tb_SearchBox"}
AddHandler tb_SearchBox.TextChanged, AddressOf tb_SearchBox_TextChanged
Item1ToolStripMenuItem.DropDownItems.Add(tb_SearchBox)
End Sub
Private Sub tb_SearchBox_TextChanged(sender As Object, e As EventArgs)
MsgBox("Success")
End Sub
End Class
【问题讨论】:
-
您的
ControlPanelclass 没有引发任何事件。它需要订阅子控件上的任何事件,然后在控件触发它们时引发自己的事件。这有时被称为“冒泡事件”