问题描述
我有一个带有父节点和两个子节点的 TreeView.每个节点都包含一个存储在 TreeViewItem 中的复选框.当用户检查父节点时,我希望将两个子节点复选框设置为 IsChecked=true,当用户取消选中父节点时,我希望两个子节点复选框设置为 IsChecked=false.
I have a TreeView with a parent node and two children node. Each of the nodes contain a checkbox stored in a TreeViewItem. I want the two children node checkboxes to be set to IsChecked=true when the user checks the parent node and I want the two children node checkboxes to be IsChecked=false when the user unchecks the parent node.
我有一个 for 循环,其中子节点复选框存储在列表中.父节点复选框选中/取消选中事件应该遍历子节点复选框列表,但我在访问列表时遇到问题.出于某种原因,该列表在父节点检查/取消检查事件中等于无".谁能解释一下我应该如何访问该列表?
I have a for loop in which the child node checkboxes are stored in a list. The parent node checkbox check/uncheck event should iterate through the child node checkbox list but I am having a problem aceess the list. For some reason the list equals "nothing" in the parent node check/uncheck event. Can anyone explain how I should be accessing that list?
这是我的代码:
Public Class Question
Dim childCheckbox As CheckBox
Dim childCheckboxes() As 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
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 child In childCheckboxes
child.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
感谢您的帮助!
推荐答案
你能不能试试换行:
Dim childCheckboxes() As CheckBox
致:
Dim childCheckboxes as new list(of CheckBox)
这篇关于VB.NET WPF NullReference 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!