VB.NET WPF NullReference异常

时间:2010-11-19 17:26:47

标签: wpf vb.net

我有一个带有父节点和两个子节点的TreeView。每个节点都包含一个存储在TreeViewItem中的复选框。我希望当用户检查父节点时,将两个子节点复选框设置为IsChecked = true,并且当用户取消选中父节点时,我希望两个子节点复选框为IsChecked = false。

我有一个for循环,其中子节点复选框存储在列表中。父节点复选框check / uncheck事件应该遍历子节点复选框列表,但是我遇到了列表问题。由于某种原因,列表在父节点check / uncheck事件中等于“nothing”。任何人都可以解释我应该如何访问该列表吗?

这是我的代码:

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

您可以尝试更改该行:

Dim childCheckboxes() As CheckBox

要:

Dim childCheckboxes as new list(of CheckBox)