问题是,当您尝试在构造函数中订阅 CurrentChanged 事件时,DependencyProperty DataIcvProperty 具有默认值 Nothing(正如您在属性注册中指定的那样) .所以NullReferenceException。
您可以使用PropertyChangeCallback 解决此问题(请参阅documentation)。
我来自 C# 世界,无法保证 VB.NET 的语法正确,但这种方法肯定会奏效:
Public Shared ReadOnly DataIcvProperty As DependencyProperty =
DependencyProperty.Register("DataIcv",
GetType(ICollectionView), GetType(DataNavigator),
New FrameworkPropertyMetadata(
Nothing,
New PropertyChangedCallback(AddressOf OnDataIcvChanged)))
那你需要实现OnDataIcvChanged这个静态方法,每次属性值改变都会调用。
Private Shared Sub OnDataIcvChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
If e.OldValue IsNot Nothing
RemoveHandler (e.OldValue As ICollectionView).CurrentChanged, AddressOf OnDataICVCurrentChanged
EndIf
If e.NewValue IsNot Nothing
AddHandler (e.NewValue As ICollectionView).CurrentChanged, AddressOf OnDataICVCurrentChanged
EndIf
End Sub
更新:
如果您的事件处理程序方法不是静态的,那么您应该通过对象实例访问它:
Private Shared Sub OnDataIcvChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
Dim DataNavigator instance = d As DataNavigator
If e.OldValue IsNot Nothing
RemoveHandler (e.OldValue As ICollectionView).CurrentChanged, AddressOf instance.OnDataICVCurrentChanged
EndIf
If e.NewValue IsNot Nothing
AddHandler (e.NewValue As ICollectionView).CurrentChanged, AddressOf instance.OnDataICVCurrentChanged
EndIf
End Sub
编辑:最终起作用的代码:
Public Shared ReadOnly DataIcvProperty As DependencyProperty = DependencyProperty.Register("DataIcv", GetType(ICollectionView), GetType(DataNavigator), New FrameworkPropertyMetadata(Nothing, New PropertyChangedCallback(AddressOf OnDataIcvChanged)))
<Description("The CollectionView (as an ICollectionView) to be passed to the DataNavigator control"), Category("Navigation Data Source")>
Public Property DataIcv As ICollectionView
Get
Return CType(GetValue(DataIcvProperty), ICollectionView)
End Get
Set(ByVal Value As ICollectionView)
SetValue(DataIcvProperty, Value)
End Set
End Property
Private Shared Sub OnDataIcvChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
Dim dn As DataNavigator = CType(d, DataNavigator)
If e.OldValue IsNot Nothing Then
RemoveHandler dn.DataIcv.CurrentChanged, AddressOf dn.OnDataICVCurrentChanged
End If
If e.NewValue IsNot Nothing Then
AddHandler dn.DataIcv.CurrentChanged, AddressOf dn.OnDataICVCurrentChanged
End If
End Sub
Private Sub OnDataICVCurrentChanged(ByVal sender As Object, ByVal e As EventArgs)
Record.Text = (DataIcv.CurrentPosition + 1).ToString
End Sub