我正在尝试使用由标签和值组成的通用小部件。该值由组合框设置。结构如下:
Structure tParam
Dim label As Label
Dim comboBox As ComboBox
Dim valueX As String
End Structure
Dim parameter1 As tParam
我想在触发SelectedIndexChanged事件时修改valueX。
现在我已经设置了
parameter1.label.text = "Id"
parameter1.comboBox.Tag = parameter1 ' the struct itself
AddHandler parameter1.comboBox.SelectedIndexChanged, AddressOf updateParam
并在处理程序
中Private Sub updateParam(sender As Object, e As System.EventArgs)
Dim parameterX As tParam = sender.Tag
With parameterX
Select Case .label.Text
Case "Id"
parameter1.valueX = .comboBox.SelectedIndex
End Select
End Sub
问题是我有很多(> 50)tParam类型的参数,我不想用select case检查每个参数名称。
请注意,我在处理程序中直接调用parameter1,因为parameterX(= sender.Tag)是只读的,因为对parameterX的任何更新都是本地的。
答案 0 :(得分:2)
我无法告诉您要做什么,但tStruct.ComboBox.Tag = Me
似乎是一种跟踪您的小部件的复杂方式。使用类,您可以内化并简化您尝试做的似乎的一些内容:
Public Class CBOWidgetItem
Private WithEvents myCBO As ComboBox
Private myLbl As Label
Public Property Name As String
Public Property Value As String
Public Sub New(n As String, cbo As ComboBox, lbl As Label)
Name = n
myCBO = cbo
myLbl = lbl
End Sub
Private Sub myCBO_SelectedIndexChanged(sender As Object,
e As EventArgs) Handles myCBO.SelectedIndexChanged
Value = myCBO.SelectedIndex.ToString
End Sub
Public Overrides Function ToString() As String
Return Name
End Function
End Class
小部件能够处理价值变化本身(再次,我不知道你在做什么)。您可能有其他包装器道具来公开窗口小部件正在管理的某些信息:
Public ReadOnly Property LabelText As String
Get
If myLbl IsNot Nothing Then
Return myLbl.Text
Else
Return ""
End If
End Get
End Property
使用它:
' something to store them in:
Private widgets As List(Of CBOWidgetItem)
...
widgets = New List(Of CBOWidgetItem)
' long form
Dim temp As New CBOWidgetItem("ID", ComboBox1, Label1)
widgets.Add(temp)
' short form:
widgets.Add(New CBOWidgetItem("foo", ComboBox2, Label2))
在其他地方如果你需要找到其中一个人:
Dim find = "ID"
Dim specificItem = widgets.Where(Function(s) s.Name = find).FirstOrDefault
If specificItem IsNot Nothing Then
Console.WriteLine(specificItem.Name)
End If
或者,您可以使用Dictionary(Of String, CBOWidgetItem)
并按名称取回它们。