So, I create a TreeViewItem (parentNode), and I add TreeViewItems into the parentNode TreeViewItem. I then add a MouseButtonEventHandler to the parentNode, and now all the TreeViewItems inside parentNode have the MouseButtonEventHandler. I've run the debugger to see if I have code that was accidentally written to add the MouseButtonHandler, but there isn't...
Edit: I did additional tests, and it even goes two levels down. Is there a way to isolate eventhandlers to only the specific node and not its children and/or parents?
public newClass() {
TreeViewItem parent = new TreeViewItem();
TreeViewItem childOne = new TreeviewItem();
addExpandClickListener(childOne);
TreeViewItem childTwo = new TreeviewItem();
TreeViewItem childThree = new TreeViewItem();
childTwo.Items.Add(childThree);
childOne.Items.Add(childTwo);
parent.Items.Add(childOne);
TreeViewObject.Items.Add(parent);
}
private void addExpandClickListener(TreeViewItem item) { item.MouseLeftButtonUp += new MouseButtonEventHandler(item_MouseClick); }
private void item_MouseClick(object sender, MouseButtonEventArgs e) {
// Define click event as handled
e.Handled = true;
if(sender != e.Source) return;
// Handle click event
TreeViewItem root = (TreeViewItem)sender;
if(root.IsExpanded == true) CollapseRecursive(root);
else root.IsExpanded = true;
//else root.ExpandSubtree();
ViewTree.Items.Refresh();
}
The area of the parentNode includes the areas of the children. Think of overlapping rectangles. If you only want to have a click to work for the text part, you'll either have to supply your own DataTemplate or use the visual tree to find the header and apply the click to that.