VS2012 WinForms中PropertyChanged子程序未触发问题求助
问题解决方法
核心原因
你在Form1里用WithEvents声明的_Class1对象,其PropertyChanged事件是和_Class1_PropertyChanged处理程序绑定的,但点击按钮时你创建了全新的tmpObj实例——这个新实例的事件并没有和Form1的处理程序关联,所以修改它的属性只会触发Class1内部的提示,而Form1的事件处理代码不会执行。
解决方案(二选一即可)
方案1:使用WithEvents声明的对象实例化
直接给WithEvents声明的_Class1赋值实例,而不是创建新的tmpObj:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click _Class1 = New Class1() _Class1.PropValue = "测试值" End Sub
因为_Class1是WithEvents修饰的,VB.NET会自动帮你绑定PropertyChanged事件到_Class1_PropertyChanged处理程序,修改属性时就能触发Form1的提示。
方案2:手动绑定新实例的事件
如果必须保留tmpObj这个新实例,需要手动给它添加事件处理绑定:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim tmpObj As New Class1() ' 手动绑定事件处理程序 AddHandler tmpObj.PropertyChanged, AddressOf _Class1_PropertyChanged tmpObj.PropValue = "测试值" End Sub
这样tmpObj的PropertyChanged事件触发时,就会调用Form1里的_Class1_PropertyChanged子程序。
额外验证:确保Class1的INotifyPropertyChanged实现正确
检查你的Class1是否正确实现了接口并触发事件,正确的示例如下:
Imports System.ComponentModel Public Class Class1 Implements INotifyPropertyChanged Private _propValue As String Public Property PropValue As String Get Return _propValue End Get Set(value As String) If _propValue <> value Then _propValue = value MessageBox.Show("Event Raised") ' 正确触发PropertyChanged事件,参数要指定属性名 RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(NameOf(PropValue))) End If End Set End Property ' 实现INotifyPropertyChanged接口的事件 Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged End Class
内容的提问来源于stack exchange,提问作者Sarangan R
相关产品推荐
相关产品推荐

