(这是对上一个问题的跟进。VB.NET WPF NullReference Exception)
我有一个带有父节点和两个子节点的TreeView。每个节点都包含一个存储在TreeViewItem中的复选框。我希望当用户检查父节点时,将两个子节点复选框设置为IsChecked = true,并且当用户取消选中父节点时,我希望两个子节点复选框为IsChecked = false。
我有一个for循环,其中子节点复选框存储在列表中。父节点的复选框检查/取消选中事件应该遍历子节点复选框列表,但是我在chkbox_AllChecked函数中遇到了childCheckboxes列表的问题(父节点的复选框检查/取消选中事件)。由于某种原因,列表是空的。我认为问题是我在For循环中尝试填充列表的方法。谁能解释我做错了什么?
这是我的代码:
Public Class Question
Dim childCheckbox As CheckBox
Dim childCheckboxes As New List(Of CheckBox)
Public Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
Dim parentCheckbox = New CheckBox
Dim parentNode = New TreeViewItem
parentCheckbox.Uid = "All Sites"
AddHandler parentCheckbox.Checked, AddressOf chkbox_AllChecked
AddHandler parentCheckbox.Unchecked, AddressOf chkbox_AllUnchecked
parentCheckbox.Content = "All Sites"
parentNode.Header = parentCheckbox
Dim i As Integer = 0
Dim childCheckboxes(sites.Length) As CheckBox
For Each osite In sites
Dim childNode = New TreeViewItem
Dim childCheckbox = New CheckBox
AddHandler childCheckbox.Checked, AddressOf chkbox_Checked
AddHandler childCheckbox.Unchecked, AddressOf chkbox_Unchecked
childCheckbox.Uid = osite.SiteName.ToString
childCheckbox.Content = osite.SiteName.ToString
childNode.Header = childCheckbox
parentNode.Items.Add(childNode)
'Add all childCheckbox to an array for use by parentChildbox methods to check/uncheck all
childCheckboxes(i) = childCheckbox
i += 1
Next
TreeView1.Items.Add(parentNode)
End Sub
Private Sub chkbox_AllChecked(ByVal sender As Object, ByVal e As RoutedEventArgs)
Dim chk = DirectCast(sender, CheckBox)
'MessageBox.Show(chk.Uid.ToString)
'This part doesn't work.
For Each c In childCheckboxes
c.IsChecked = True
Next
End Sub
Private Sub chkbox_Checked(ByVal sender As Object, ByVal e As RoutedEventArgs)
Dim chk = DirectCast(sender, CheckBox)
'MessageBox.Show("Check!")
MessageBox.Show(chk.Uid.ToString)
End Sub
Private Sub chkbox_Unchecked(ByVal sender As Object, ByVal e As RoutedEventArgs)
Dim chk = DirectCast(sender, CheckBox)
'MessageBox.Show("Uncheck!")
MessageBox.Show(chk.Uid.ToString)
End Sub
End Class
感谢您的帮助!
答案 0 :(得分:0)
好的,我想出来了。
1)我不想要这一行:Dim childCheckboxes(sites.Length)作为CheckBox 因为那是一个不是列表的数组。
2)删除第一行后,我需要更改:childCheckboxes(i)= childCheckbox 对此:childCheckboxes.Add(childCheckbox)
就是这样!完成。其余的工作。