The WPF TreeView selects the event to be executed twice to obtain the solution of the parent node of the TreeView. wpftreeview
1. Run the TreeView selected event twice.
Very often, we need to execute some code inSelectedItemChanged
Depending on the selectedTreeViewItem
.SelectedItemChanged
Is called twice. This is due to stealing focus from the main window, which is screwing something up.
What we have to do to avoid this is simply delay the call to our code, I. e .,MyFunction()
Which we need to execute inSelectedItemChanged
. Here's a workaround which delays the call to open the new window until the item selection code finishes up:
private delegate void NoArgDelegate(); void Window1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e){ Dispatcher.BeginInvoke(DispatcherPriority.Background, (NoArgDelegate)delegate { MyFunction(); });}
2. Obtain the parent node from Treeview
Private void treeviewincluselecteditemchanged (object sender, RoutedPropertyChangedEventArgs <object> e) {// node (subnode or root node) TreeViewItem item = treeView1.SelectedItem as TreeViewItem; // obtain the parent node TreeViewItem parent = item. parent as TreeViewItem; // determines whether the parent node exists if (Parent! = Null) {// displays the parent node information. The Header information MessageBox is displayed here. show ("parent node Header:" + parent. header. toString ();} else {MessageBox. show ("no parent node! ");}}
In wpf, select a child node of treeview and obtain the content of all parent nodes of the child node for database query.
Example on csdn (for reference only): private void treeView1_SelectedItemChanged (object sender, RoutedPropertyChangedEventArgs <object> e)
{
TreeViewItem item = (TreeViewItem) treeView1.SelectedItem;
TreeViewItem it = new TreeViewItem ();
If (! Item. HasItems)
{
If (item. Parent! = Null & (item. Parent is TreeViewItem ))
{
It = (TreeViewItem) item. Parent;
MessageBox. Show (it. Header. ToString () + (item. Parent is TreeViewItem). ToString ());
}
Else
{
MessageBox. Show (item. Header. ToString ());
}
}
}
How does TreeView obtain the parent node when selecting a subnode?
Treeview. selectednode. parentnode
This attribute seems to exist. You can find the parent.