首页 > 代码库 > 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("没有父节点!"); } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。