如您在下面的代码中看到的,我创建了一个名为Period的自定义控件,该控件从Listbox继承。在其中,我声明了一个名为'Subjects'的只读依赖属性。当在WPF窗口上放置一个句点时,一切运行正常。但是,当我放置多个时,出现标题中提到的错误。
这是期间类:
Public Class Period
Inherits System.Windows.Controls.ListBox
'-------- PROPERTIES --------'
Public ReadOnly Property Subjects() As ObservableCollection(Of Subject)
Get
Return Me.GetValue(SubjectsProperty)
End Get
End Property
Private ReadOnly SubjectsPropertyKey As DependencyPropertyKey = DependencyProperty.RegisterReadOnly("Subjects", GetType(ObservableCollection(Of Subject)), GetType(Period), New FrameworkPropertyMetadata(New ObservableCollection(Of Subject)))
Public ReadOnly SubjectsProperty As DependencyProperty = SubjectsPropertyKey.DependencyProperty
'-------- SUBROUTINES ---------'
Shared Sub New()
'This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class.
'This style is defined in themes\generic.xaml
DefaultStyleKeyProperty.OverrideMetadata(GetType(Period), New FrameworkPropertyMetadata(GetType(Period)))
End Sub
Public Sub New()
MyBase.New()
Me.SetValue(SubjectsPropertyKey, New ObservableCollection(Of Subject))
End Sub
'-------- METHODS ---------'
Public Sub AddSubject(ByRef subject As Subject)
If Me.CheckForDuplicates(subject) = True Then
MsgBox("This subject is already present in this period.")
Else
Dim SubjectsList As New ObservableCollection(Of Subject)
SubjectsList = Me.GetValue(SubjectsProperty)
SubjectsList.Add(subject)
Me.SetValue(SubjectsPropertyKey, SubjectsList)
End If
End Sub
Public Sub RemoveSubject(ByRef subject As Subject)
If Me.CheckForDuplicates(subject) = False Then
MsgBox("This subject is not present in this period.")
Else
Dim SubjectsList As New ObservableCollection(Of Subject)
SubjectsList = Me.GetValue(SubjectsProperty)
SubjectsList.Remove(subject)
Me.SetValue(SubjectsPropertyKey, SubjectsList)
End If
End Sub
Public Function CheckForDuplicates(ByRef subject As Subject) As Boolean
Dim Conflict As Boolean
If Subjects.Contains(subject) Then
Conflict = True
End If
Return Conflict
End Function
Private Sub Period_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized
Me.ItemsSource = Subjects
End Sub
End Class
这是窗口的代码:
<Grid Background="#FF2B2B2B">
<local:Period HorizontalAlignment="Left" VerticalAlignment="Top"/>
<local:Period HorizontalAlignment="Left" VerticalAlignment="Top"/>
</Grid>
SubjectsPropertyKey和SubjectsProperty必须为Shared
。否则,它将尝试在Period类的每个实例中注册Subject,并且在成功注册后失败。
请参阅MSDN中的“示例”部分。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句