因此,我创建了一个 TreeViewItem(parentNode),并将 TreeViewItems 添加到 parentNode TreeViewItem 中。然后我将 MouseButtonEventHandler 添加到 parentNode,现在 parentNode 内的所有 TreeViewItems 都有 MouseButtonEventHandler。我已经运行调试器来查看是否有意外编写的添加 MouseButtonHandler 的代码,但没有...
编辑:我做了额外的测试,它甚至下降了两个级别。有没有办法将事件处理程序隔离到仅特定节点而不是其子节点和/或父节点?
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();
}