我正在尝试在包含控件的所有子项的List(Of)类型的WPF中创建依赖项对象。尽管采取了here概述的预防措施,但在为属性分配值时似乎创建了单例。当我分配一个值时,会添加一个值乘以该类的实例数。
这是我的代码:
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