我希望在表单中有一个标签,其文本值会根据类实例的值而改变.看起来我可以将标签的文本值绑定到对象dataSource.当我尝试这个似乎不起作用. Me.Label4.DataBindings.Add(New System.Windows.Forms.Bi
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
我认为我所做的是绑定一个类,而不是一个类的实例.考虑一下,我真正想做的是将一个类的实例绑定到一个标签……怎么样?
这可能吗?
要将事件添加到您的班级:
>更改类定义以实现INotifyPropertyChanged
>添加相应的PropertyChanged事件
>将自动实现的属性更改为展开的属性并引发事件.
以下是类中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.
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属性,以便您可以看到新值.