首页 > 代码库 > WPF TreeView 选择事件执行两次,获取TreeView的父节点的解决方法

WPF TreeView 选择事件执行两次,获取TreeView的父节点的解决方法

1.TreeView选择事件执行两次

Very often, we need to execute some code in SelectedItemChanged depending on the selected TreeViewItem. ButSelectedItemChanged 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.Treeview获取父节点

   private void treeView1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)        {            //节点(是子节点或者是根节点)            TreeViewItem item = treeView1.SelectedItem as TreeViewItem;             //获取父节点            TreeViewItem parent = item.Parent as TreeViewItem;            //判断父节点是否存在            if (parent != null) {                //显示父节点信息,这里显示 Header 信息                MessageBox.Show("父节点的Header:" + parent.Header.ToString());            } else {                MessageBox.Show("没有父节点!");            }         }