11
votes

I have a Winform application where I am using TreeView. Some users of this application have a problem that they must double click on a node to expand it. So I added this code to use single click to expand nodes:

Private Sub MyTreeView_NodeMouseClick(sender As System.Object, 
     e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles MyTreeView.NodeMouseClick

    If e.Node.IsExpanded Then
        e.Node.Collapse()
    Else
        e.Node.Expand()
    End If

End Sub

This works but I noticed strange behavior regarding clicking on a nodes. I noticed that there are 2 places with different behavior. First place is with +/- symbol and dots next to it (first circle in the picture), second place is a text of the node (second circle):

enter image description here

Normally single click on the first place is enough to expand node and double click must be done on the second place to expand node. Then when I use my code, single click on the second place is enough to expand the node but when I do single click on the first place, the node is expanded and collapsed.

Why the user must do twice more clicks on the second place to expand node? What can I do to expand nodes with single click on both places? Thank you guys!

1

1 Answers

13
votes

The plus/minus is still considered part of the Node - and when the user clicks it, your code toggles the expansion but the framework continues and does the same.

Add to your code to not act on the plus/minus:

private static void TreeView_OnNodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
    var hitTest = e.Node.TreeView.HitTest(e.Location);
    if (hitTest.Location == TreeViewHitTestLocations.PlusMinus)
        return;

    if (e.Node.IsExpanded)
        e.Node.Collapse();
    else
        e.Node.Expand();
}