Why do items in TreeViewItem inherit the event handlers of parent?

眉间皱痕 提交于 2019-12-24 01:18:31

问题


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();
}

回答1:


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.



来源:https://stackoverflow.com/questions/11334651/why-do-items-in-treeviewitem-inherit-the-event-handlers-of-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!