我希望在表单中有一个标签,其文本值会根据类实例的值而改变。看起来我可以将标签的文本值绑定到对象dataSource。当我尝试这个似乎不起作用。
Me.Label4.DataBindings.Add(New System.Windows.Forms.Binding("Text", Me.ItemInfoBindingSource, "ItemNumber", True, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged))
我的itemInfoBindingSource:
Me.ItemInfoBindingSource.DataSource = GetType(CFP.ItemInfo)
和类定义:
Public Class ItemInfo
Public Property ItemNumber As String = "rename"
Public Property Description As String
Public Property FileLocation As String
Public Property CompileHistory As List(Of CompileHistory)
End Class
我认为我所做的就是绑定一个类,而不是一个类的实例。考虑一下,我真正想做的是将一个类的实例绑定到一个标签......怎么样? 这可能吗?
答案 0 :(得分:8)
是的,这是可能的,但您需要引发事件以让标签知道该属性已更改。如果您使用类似BindingList的类型,这将自动完成,但您尝试绑定到不会引发PropertyChanged事件的String
。
将事件添加到您的班级:
以下是您班级中ItemNumber属性的这些更改的结果:
Public Class ItemInfo
Implements System.ComponentModel.INotifyPropertyChanged
Private _itemNumber As String = "rename"
Public Property ItemNumber As String
Get
Return _itemNumber
End Get
Set(value As String)
_itemNumber = value
RaiseEvent PropertyChanged(Me,
New System.ComponentModel.PropertyChangedEventArgs("ItemNumber"))
End Set
End Property
Public Event PropertyChanged(sender As Object,
e As System.ComponentModel.PropertyChangedEventArgs) _
Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
End Class
我在表单中添加了一个文本框和标签,在Form.Load
事件中添加了数据绑定,添加了一个名为ItemInfo的ItemInfoBindingSource字段,并更新了TextBox.TextChanged
事件中的ItemNumber。 / p>
Private ItemInfoBindingSource As New ItemInfo
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.DataBindings.Add("Text", Me.ItemInfoBindingSource, "ItemNumber")
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) _
Handles TextBox1.TextChanged
ItemInfoBindingSource.ItemNumber = TextBox1.Text
End Sub
现在,当您在文本框中键入时,会调用ItemNumber.Set,并引发一个事件以让任何侦听都知道它已被更改。标签正在侦听,它会更新其Text属性,以便您可以看到新值。