以下のコードでわかるように、Listbox から継承する Period という名前のカスタム コントロールを作成しました。その中で、「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>