在运行时添加TreeView时,如何向TreeNode添加AfterCheck事件处理程序

时间:2015-09-04 15:28:41

标签: vb.net

我正在尝试为TreeNode AfterCheck事件创建一个事件处理程序。我想在检查父项时检查所有孩子。唯一的问题是,在运行时创建TreeView时,我不确定如何执行此操作。此代码假定我已在表单上有一个名为treeView1的TreeView。用TreeView取代treeView1需要做什么呢?

' Updates all child tree nodes recursively. 
    Private Sub CheckAllChildNodes(treeNode As TreeNode, nodeChecked As Boolean)
        Dim node As TreeNode
        For Each node In treeNode.Nodes
            node.Checked = nodeChecked
            If node.Nodes.Count > 0 Then
                ' If the current node has child nodes, call the CheckAllChildsNodes method recursively. 
                Me.CheckAllChildNodes(node, nodeChecked)
            End If
        Next node
    End Sub

    ' NOTE   This code can be added to the BeforeCheck event handler instead of the AfterCheck event. 
    ' After a tree node's Checked property is changed, all its child nodes are updated to the same value. 
    Private Sub node_AfterCheck(sender As Object, e As TreeViewEventArgs) Handles treeView1.AfterCheck
        ' The code only executes if the user caused the checked state to change. 
        If e.Action <> TreeViewAction.Unknown Then
            If e.Node.Nodes.Count > 0 Then
                ' Calls the CheckAllChildNodes method, passing in the current  
                ' Checked value of the TreeNode whose checked state changed.  
                Me.CheckAllChildNodes(e.Node, e.Node.Checked)
            End If
        End If
    End Sub

更正代码

我添加了树视图,我添加了

AddHandler newTree.AfterCheck, AddressOf node_AfterCheck

然后我对上面的代码所做的就是删除它所说的

Handles treeView1.AfterCheck

在事件处理程序声明中。

我还能够添加另一个事件处理程序,如果将鼠标悬停在子节点上,则将光标更改为Cursors.No,如果将鼠标悬停在父节点上,则将其更改为手。这与aftercheck处理程序在同一位置添加。

AddHandler newTree.NodeMouseHover, AddressOf node_MouseOver

这是实际的事件处理程序

' Event handler for node mouse over
    Private Sub node_MouseOver(sender As Object, e As TreeNodeMouseHoverEventArgs)

        If e.Node.Tag > 99999999 Then
            sender.Cursor = Cursors.Hand
        Else
            sender.Cursor = Cursors.No
        End If

    End Sub

1 个答案:

答案 0 :(得分:2)

可以指示在程序中其他位置添加的新TreeNode个对象使用相同的AfterCheck方法,例如通过写作

Dim myTreeView As New TreeView 'create a new tree view
AddHandler myTreeView.AfterCheck, AddressOf node_AfterCheck 'add this speficic AfterCheck callback to the new TreeView.
'Add myTreeView to the GUI..