我试图在 WPF 中创建一个 List(Of) 类型的依赖对象,其中包含控件的所有子项。尽管采取 了此处概述的预防措施,但似乎在我为属性分配值时创建了一个单例。当我分配一个值时,该值乘以类的实例数。
这是我的代码:
Public Class Period
Inherits ListBox
'-------- PROPERTIES --------'
Private Property Subjects() As List(Of Subject)
Get
Return Me.GetValue(SubjectsProperty)
End Get
Set(value As List(Of Subject))
Me.SetValue(SubjectsProperty, value)
End Set
End Property
Private Shared ReadOnly SubjectsProperty As DependencyProperty = DependencyProperty.Register("Subjects", GetType(List(Of Subject)), GetType(Period), New FrameworkPropertyMetadata(New List(Of Subject)))
Public Sub New()
MyBase.New()
Me.Subjects = New List(Of Subject) 'Reason: stop it from adding values to defult value collection. See:http://msdn.microsoft.com/en-us/library/aa970563.aspx
End Sub
此子例程用于在添加子项时刷新属性:
Private Sub RefreshSubjectsProperty()
Dim ListOfSubjects As New List(Of Subject)
Dim Subject As New Subject
Dim Entry As New PeriodEntry
For Each Entry In LogicalTreeHelper.GetChildren(Me)
Subject.SubjectName = Entry.SubjectName
Subject.Teacher = Entry.Teacher
Subject.Students = Entry.Students
ListOfSubjects.Add(Subject)
Next
Me.Subjects = ListOfSubjects
End Sub