Why isn't there a SelectedNodeChanged event for Windows.Forms.TreeView?

前端 未结 4 858
深忆病人
深忆病人 2020-12-10 10:04

The System.Web.UI.WebControls.TreeView class offers this event, but the Forms version of TreeView doesn\'t. What\'s the equivalent in the Forms world? I\'m using AfterSelect

相关标签:
4条回答
  • 2020-12-10 10:32

    There's none in WinForms TreeView. To quote MSDN for TreeView.AfterSelect:

    This event does not occur when the node is unselected. To detect this occurrence, handle the Control.MouseUp event and test the TreeNode.IsSelected property.

    Yes, this sucks.

    0 讨论(0)
  • 2020-12-10 10:33

    OK, this is an OOOLD question, but the problem really annoyed me. I made this little helper class -- it works for me.

    Public Class TreeViewSelectedNodeChangeEventHandler
    Public Event SelectedTreeNodeChanged(sender As Object, e As EventArgs)
    
    Private m_selectedNode As TreeNode
    Private WithEvents m_tvw As TreeView
    
    Public Shared Function FromTree(tree As TreeView) As TreeViewSelectedNodeChangeEventHandler
        If Not IsNothing(tree) Then
            Return New TreeViewSelectedNodeChangeEventHandler(tree)
        End If
        Return Nothing
    End Function
    
    ''' <summary>Assigns 'Value' to 'this' and returns 'Value'.</summary>
    Private Function InLineAssign(Of V)(ByRef this As V, value As V) As V
        Dim ret = value
        this = value
        Return ret
    End Function
    

    May add other triggers, e.g. Control.Enter, MouseUp etc. etc.

    Private Sub keyUp(sender As Object, e As KeyEventArgs) Handles m_tvw.KeyUp
        If Not Me.m_selectedNode Is InLineAssign(Me.m_selectedNode, m_tvw.SelectedNode)  
    

    Then

        RaiseEvent SelectedTreeNodeChanged(m_tvw, EventArgs.Empty)
            End If
        End Sub
        Private Sub New(tv As TreeView)
            m_tvw = tv
        End Sub
    End Class
    
    0 讨论(0)
  • 2020-12-10 10:37

    There's nothing wrong with using AfterSelect.

    However, note that it won't fire if the selection is cleared (if SelectedNode becomes null) Instead, you can handle MouseUp, as recommended in the documentation.

    0 讨论(0)
  • 2020-12-10 10:39

    There's none in WinForms TreeView. To quote MSDN for TreeView.AfterSelect:

    This event does not occur when the node is unselected. To detect this occurrence, handle the Control.MouseUp event and test the TreeNode.IsSelected property.

    You'd better use TreeView.NodeMouseClick event combined with AfterSelect. AfterSelect isn't called when you select the previously selected SelectedNode. So just call AfterSelect when necessary, e.Node helps you.

    private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node == tv.SelectedNode)
                treeView1_AfterSelect(sender, null);
        }
    
    0 讨论(0)
提交回复
热议问题