码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-08-21 19:12:24      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:blog   os   io   ar   div   cti   log   new   

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("没有父节点!");
            }
 
        }

  

  

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

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

标签:blog   os   io   ar   div   cti   log   new   

原文地址:http://www.cnblogs.com/smiler/p/3927628.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!