Get TreeViewItem for TreeView logical element

后端 未结 1 1653
北荒
北荒 2021-01-27 19:57

My tree view seems like this


            
                    


        
相关标签:
1条回答
  • 2021-01-27 20:07

    if I got you correctly you want to retrieve the TreeViewItem from the SelectedItem

    so you can make use of ItemContainerGenerator

            ItemContainerGenerator gen = ArticlesTreeView.ItemContainerGenerator;
            TreeViewItem item = gen.ContainerFromItem(ArticlesTreeView.SelectedItem) as TreeViewItem;
    

    Get TreeViewItem from nested items

    due to the reason that every TreeViewItem has it's own ItemContainerGenerator so in order to find the container from the nested items we need to recurse the depth of the tree

        private void ArticlesTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            var item = ContainerFromItem(ArticlesTreeView.ItemContainerGenerator, ArticlesTreeView.SelectedItem);
        }
    
        private static TreeViewItem ContainerFromItem(ItemContainerGenerator containerGenerator, object item)
        {
            TreeViewItem container = (TreeViewItem)containerGenerator.ContainerFromItem(item);
            if (container != null)
                return container;
    
            foreach (object childItem in containerGenerator.Items)
            {
                TreeViewItem parent = containerGenerator.ContainerFromItem(childItem) as TreeViewItem;
                if (parent == null)
                    continue;
    
                container = parent.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
                if (container != null)
                    return container;
    
                container = ContainerFromItem(parent.ItemContainerGenerator, item);
                if (container != null)
                    return container;
            }
            return null;
        }
    
    0 讨论(0)
提交回复
热议问题