WPF 树视图项
我正在使用以下循环遍历 xml 文档的方法创建一个 TreeView。
但是,当选择任何 TreeViewItem
时,层次结构中的所有节点都会获取事件触发器,而不仅仅是选定的 TreeViewItem
。
例如,假设我们选择一个节点的孙子。所有节点(包括孙子、子节点、父节点)都触发相同的事件。
换句话说,我们期望只有孙子触发关联的事件,而该事件应该只被调用一次,但最终会为所选项目的层次结构的所有节点调用 3 次。
这是代码:
TreeViewItem getTreeViewItemWithHeader(XmlNode node)
{
TreeViewItem tvi = new TreeViewItem();
tvi.Header = node.Name;//hdr;
tvi.Tag = node.Attributes["Tag"].Value;
tvi.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(tvi_PreviewMouseLeftButtonDown);
tvi.Selected += new RoutedEventHandler(tvi_Selected);
return tvi;
}
如果您有任何建议,请告诉我,谢谢
N
I am creating a TreeView
using the following method looping through an xml document.
However when any TreeViewItem
is selected all the nodes in the hierarchy are getting the event triggers instead of just the selected TreeViewItem
.
For example let's say we select the grandchild of a node. All the nodes including grandchild, child, parent are triggering the same event.
In other words we would expect only the grandchild trigger the associated event whereas and the event should get called only once but it ends up being called 3 times for all the nodes of the hierarchy of the selected item.
Here is the code:
TreeViewItem getTreeViewItemWithHeader(XmlNode node)
{
TreeViewItem tvi = new TreeViewItem();
tvi.Header = node.Name;//hdr;
tvi.Tag = node.Attributes["Tag"].Value;
tvi.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(tvi_PreviewMouseLeftButtonDown);
tvi.Selected += new RoutedEventHandler(tvi_Selected);
return tvi;
}
Please let me know if you have any suggestions, thanks
N
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是正常工作的。
PreviewMouseLeftButtonDown
事件是路由事件(在本例中策略是隧道)。这意味着可视化树的根首先获取事件,然后向下工作,直到到达最初触发事件的控件。MouseLeftButtonDown
和Selected
事件也被路由,但其策略是冒泡 - 这意味着事件沿着可视化树向上移动,从触发事件的控件开始。如果您希望不再发送路由事件,请将传入的
RoatedEventArgs
的Handled
属性设置为true
。This is working correctly. The
PreviewMouseLeftButtonDown
event is a routed event (in this case the strategy is tunneling). This means that the root of the visual tree gets the event first, and it works its way down until it reaches the control that originally triggered the event. TheMouseLeftButtonDown
andSelected
events is also routed, but its strategy is bubbling - this means that the event works its way up the visual tree, starting with the control that triggered the event.If you want a routed event to not continue to be sent, set the
Handled
property of theRoutedEventArgs
passed in totrue
.