我遇到了一个问题我不知道是否有可能阻止它。我认为默认设计是这样的。
我编写了一个由XML填充的树视图列表,每个节点在选中时都填充了一些文本框。根据其类型,它将触发不同的功能。
问题在于,当我选择一个孩子时,它似乎会触发所有父母treeviewitem的“IsSelecting”一直到顶部,这反过来触发了相关的功能,我不希望这样。
任何想法如何防止IsSelected的这种“反向继承的排序”?
示例(使用下面的代码检查):选择“节点”将触发“Node_Selected”,“Dialog_Selected”,“Actor_Selected”。
感谢您的帮助。
致以最诚挚的问候,
仅供上下文使用
private void Window_Loaded(object sender, RoutedEventArgs e)
{
XmlDocument document = new XmlDocument();
document.Load("XML/ActorsDialogs.xml");
XmlNodeList actors = document.SelectNodes("/dialogs/actor");
foreach (XmlNode actor in actors)
{
TreeViewItem newActor = new TreeViewItem();
newActor.Header = actor.SelectSingleNode("actorname").InnerText;
newActor.Selected += new RoutedEventHandler(Actor_Selected);
XmlNodeList dialogs = actor.SelectNodes("dialog");
foreach (XmlNode dialog in dialogs)
{
TreeViewItem newdialog = new TreeViewItem();
newdialog.Header = "Dialog:" + dialog.SelectSingleNode("dialogID").InnerText;
newdialog.Selected += new RoutedEventHandler(Dialog_Selected);
BuildNodes(newdialog, dialog);
newActor.Items.Add(newdialog);
}
ActorsList.Items.Add(newActor);
}
}
private void BuildNodes(TreeViewItem treeNode, XmlNode parentElement)
{
foreach (XmlNode child in parentElement.ChildNodes)
{
if (child.Name == "node" || child.Name == "reply")
{
XmlElement childElement = child as XmlElement;
TreeViewItem childTreeNode = new TreeViewItem();
string ID = child.SelectSingleNode(child.Name + "ID").InnerText;
childTreeNode.Header = childElement.Name + ":" + ID;
switch (child.Name)
{
case "node":
childTreeNode.Selected += new RoutedEventHandler(Node_Selected);
break;
case "reply":
childTreeNode.Selected += new RoutedEventHandler(Reply_Selected);
break;
default:
break;
}
treeNode.Items.Add(childTreeNode);
BuildNodes(childTreeNode, childElement);
}
}
}
private void Actor_Selected(object sender, RoutedEventArgs e){}
private void Dialog_Selected(object sender, RoutedEventArgs e){}
private void Node_Selected(object sender, RoutedEventArgs e){}
private void Reply_Selected(object sender, RoutedEventArgs e){}
答案 0 :(得分:2)
在事件处理程序中,您可以设置e.Handled = true。这样可以防止事件冒泡到树上。
private void Node_Selected(object sender, RoutedEventArgs e)
{
e.Handled = true; //this will prevent the event from bubbling up to parents;
//Do the rest of the code here.
}
有关RoutedEvents的更多信息,请参阅https://msdn.microsoft.com/en-us/library/ms742806%28v=vs.110%29.aspx。这些活动包括树上的冒泡活动和沿树下的隧道活动。