The other day I needed to implement a double click handler for a standard WPF TreeView.
Among other things, the handler was supposed to expand / collapse the clicked node of the tree view.
The implementation was easy, I closed the task and went on to program more interesting things.
Then, by chance testing, it turned out that when double clicking a leaf node,
the parent node was being collapsed. First, I thought that the clicked node was being
identified incorrectly or that there's another bug.
A quick inspection revealed nothing of that sort.
Another possibility was the incorrect handling of event bubbling,
but after some testing it looked like that wasn't the problem either
(for instance, setting e.Handled to True changes nothing).
After some searching on the Internet, the answer still wasn't clear until I visited this discussion
on StackOverflow.
It seems that double click events are reported for the clicked node as well as for all parent nodes.
I don't really get what the idea behind this was...
Anyway, it turns out that the simplest solution mentioned
at the bottom of the discussion was the best one (for the code here, at least):
Private Sub ItemMouseDoubleClick(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
Dim item As TreeViewItem = CType(sender, TreeViewItem)
If item.IsSelected Then
Dim folderNode As Node = CType(item.DataContext, Node)
...
folderNode.IsExpanded = Not folderNode.IsExpanded
End If
End Sub
Just check if the current item is the selected item and that's it.
HTH
Top
|