我有一个下拉列表,其中包含星期几到星期日的星期几。它填充了用户定义的两个值类型,将一周中的数字日映射到它的名称。
Public Structure WeekDays
Public ID As Integer
Public Text As String
Public Overrides Function ToString() As String
Return Me.Text
End Function
End Structure
我想要绑定的对象有一个整数属性DayOfWeek,我想将下拉列表中所选项的ID值绑定到Object上的DayOfWeek属性。例如。用户选择星期四,并将ID 4传递给对象。
在代码中我可以检索SelectedItem的UDT,但是我无法确定要绑定到的组合框上的哪个属性。
数据绑定似乎对普通文本框非常有效,但在处理更复杂的控件时似乎更加谨慎。
更新:我正在寻找的是Binding语句。例如。既不...
oB = New Binding("SelectedItem", Payroll, "DayOfWeek")
oB = New Binding("SelectedItem.ID", Payroll, "DayOfWeek")
......有效。第一个被忽略(可能是因为SelectedItem属性为Nothing),而第二个失败并出现“无法绑定...”错误。
答案 0 :(得分:1)
创建属性,
Public Structure WeekDays
Private _ID As Integer
Private _Text As String
Public Sub New(ByVal ID As Integer, ByVal Text As String)
Me._ID = ID
Me._Text = Text
End Sub
Public Overrides Function ToString() As String
Return Me._Text
End Function
Public Property ID() As Integer
Get
Return _ID
End Get
Set(ByVal value As Integer)
_ID = value
End Set
End Property
Public Property Text() As String
Get
Return _Text
End Get
Set(ByVal value As String)
_Text = value
End Set
End Property
End Structure
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim items As New List(Of WeekDays)
items.Add(New WeekDays(1, "A"))
items.Add(New WeekDays(2, "B"))
Dim lb As New ListBox
lb.DataSource = items
lb.ValueMember = "ID"
lb.DisplayMember = "Text"
AddHandler lb.SelectedIndexChanged, AddressOf Item_Sel
Me.Controls.Add(lb)
TextBox1.DataBindings.Add(New Binding("Text", items, "Text"))
Dim cb As New ComboBox
cb.DataSource = items
cb.DisplayMember = "Text"
cb.ValueMember = "ID"
cb.DataBindings.Add("SelectedValue", items, "ID")
cb.Location = New Point(100, 100)
Me.Controls.Add(cb)
TextBox1.DataBindings.Add(New Binding("Text", items, "ID"))
End Sub
Public Sub Item_Sel(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim obj As Object = CType(sender, ListBox).SelectedValue
MsgBox(obj)
End Sub
End Class
答案 1 :(得分:1)
好的,所以我找到了一个可能的解决方案。
我创建了自己的ComboBox控件,它继承了标准的WinForms.ComboBox,并添加了一个名为SelectedID的额外Integer属性。
Public Structure NumericUDT
Public ID As Integer
Public Text As String
Public Sub New(ByVal iID As Integer, ByVal sText As String)
Me.ID = iID
Me.Text = sText
End Sub
Public Overrides Function ToString() As String
Return Me.Text
End Function
End Structure
Public Property SelectedID() As Integer
Get
Dim uItem As NumericUDT
Dim iID As Integer
If (MyBase.SelectedItem Is Nothing) Then
iID = 0
Else
uItem = DirectCast(MyBase.SelectedItem, NumericUDT)
iID = uItem.ID
End If
Return iID
End Get
Set(ByVal value As Integer)
Dim uItem As NumericUDT
Dim uFound As NumericUDT = Nothing
For Each uItem In MyBase.Items
If uItem.ID = value Then
uFound = uItem
Exit For
End If
Next
MyBase.SelectedItem = uFound
End Set
End Property
这允许我绑定到SelectedID属性......
oB = New Binding("SelectedID", Payroll, "PayDay")
......似乎工作正常。