As you can see in the code below I have created a custom control named Period that inherits from Listbox. In it I have declared a read-only dependancy property named 'Subjects'. When a single Period is placed on the WPF window everything runs fine. However, when I place more than one I get the error mentioned in the title.
Here is the Period Class:
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
Here is the code for the window:
<Grid Background="#FF2B2B2B">
<local:Period HorizontalAlignment="Left" VerticalAlignment="Top"/>
<local:Period HorizontalAlignment="Left" VerticalAlignment="Top"/>
</Grid>