Exemple #1
0
        private void TreeViewItem_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var topic = (e.OriginalSource as FrameworkElement)?.DataContext as DocTopic;

            if (topic == null)
            {
                return;
            }

            if (e.ChangedButton == MouseButton.Left)
            {
                _lastMouseDownPoint = e.GetPosition(TreeTopicBrowser);
            }

            if (!HandleSelection(topic))
            {
                return;
            }

            if (TreeTopicBrowser.SelectedItem is DocTopic)
            {
                TreeViewItem tvi = e.OriginalSource as TreeViewItem;
                tvi?.BringIntoView();
            }
        }
Exemple #2
0
        private void TreeTopicBrowser_Selected(object sender, RoutedEventArgs e)
        {
            e.Handled = true; // don't bubble up through parents

            var topic = TreeTopicBrowser.SelectedItem as DocTopic;

            if (topic != null)
            {
                SelectedTopic = topic;

                TreeViewItem tvi = e.OriginalSource as TreeViewItem;
                tvi?.BringIntoView();
            }
        }
Exemple #3
0
 private void TreeViewItem_Selected(object sender, RoutedEventArgs e)
 {
     if (sender is TreeViewItem)
     {
         tviSelected = sender as TreeViewItem;
         if (tviSelected != null)
         {
             SelectedFile = tviSelected.DataContext as FileContainer;
             tviSelected.BringIntoView();
         }
         e.Handled = true;
     }
     else
     {
         tviSelected = null;
     }
 }
        private void Select(TreeViewItem element)
        {
            if (element.IsSelected)
            {
                return;
            }

            element.IsSelected = true;
            _lastSelectedItem  = element;
            SelectedTreeViewItems.Add(element);
            element.BringIntoView();

            if (AutoExpandSelected)
            {
                TryExpandTree(element);
            }
        }
 void CollapseTargetNode(TreeViewItem tvi, object NodeName)
 {
     if (tvi.Header.ToString() == NodeName.ToString())
     {
         tvi.IsExpanded = false;
         tvi.BringIntoView();
         return;
     }
     if (tvi.HasItems)
     {
         foreach (var item in tvi.Items)
         {
             TreeViewItem temp = item as TreeViewItem;
             CollapseTargetNode(temp, NodeName);
         }
     }
 }
Exemple #6
0
        static void OnTreeViewItemSelected(object sender, RoutedEventArgs e)
        {
            // Only react to the Selected event raised by the TreeViewItem
            // whose IsSelected property was modified. Ignore all ancestors
            // who are merely reporting that a descendant's Selected fired.
            if (!Object.ReferenceEquals(sender, e.OriginalSource))
            {
                return;
            }

            TreeViewItem item = e.OriginalSource as TreeViewItem;

            if (item != null)
            {
                item.BringIntoView();
            }
        }
        static void OnTreeViewItemSelected(object sender, RoutedEventArgs e)
        {
            // Only react to the Selected event raised by the TreeViewItem
            // whose IsSelected property was modified. Ignore all ancestors
            // who are merely reporting that a descendant's Selected fired.
            if (!Object.ReferenceEquals(sender, e.OriginalSource))
            {
                return;
            }
            TreeViewItem item = e.OriginalSource as TreeViewItem;

            if (item != null)
            {
                item.BringIntoView();
            }
            //item.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Loaded, new DispatcherOperationCallback(ScrollItemIntoView), item);
        }
        /// <summary>
        /// Initializes the "system definition" tree.
        /// </summary>
        private void LoadSystemDefSet()
        {
            string prevSelSystem = AppSettings.Global.GetString(AppSettings.NEWP_SELECTED_SYSTEM,
                                                                "[nothing!selected]");

            TreeViewItem selItem = PopulateNodes(prevSelSystem);

            if (selItem != null)
            {
                selItem.IsSelected = true;
                selItem.BringIntoView();
            }

            targetSystemTree.Focus();

            Debug.WriteLine("selected is " + targetSystemTree.SelectedItem);
        }
        /// <summary>
        /// Ensures that a node for a given item (and all its
        /// ancestors) has been created and selects it immediately.<br/>
        /// This method basically expands all ancestors of the submitted
        /// <paramref name="item"/> which makes sure the node
        /// will be available.
        /// </summary>
        /// <param name="item">The item that should be represented
        /// by an existing tree node.</param>
        /// <exception cref="InvalidOperationException">If the item's
        /// ancestor list does not lead back to the root items because
        /// the item does not belong to the tree, or the tree's rendered
        /// nodes and bound data are out of sync.</exception>
        protected void SelectItemNode(T item)
        {
            string itemKey = GetItemKey(item);

            //make sure all of the item's ancestors which will be expanded
            //-> this ensures the item will be visible on the tree when
            //we render it.
            List <T> parentList = GetParentItemList(item);

            ItemCollection items = RootNode == null ? Tree.Items : RootNode.Items;

            foreach (T parent in parentList)
            {
                string parentKey = GetItemKey(parent);

                //expand the parent node, than move a level lower
                TreeViewItem parentNode = TryFindItemNode(items, parentKey, false);

                //if we don't find the parent, the tree's nodes are not up-to-date
                //which means we should probably refresh - write to debug output...
                if (parentNode == null)
                {
                    string msg = "Cannot create a tree node for item {0} as its parent item {1} is not part of the tree's hierarchy. This is a strong indicator that data and the UI structure are out of sync.";
                    msg = String.Format(msg, itemKey, parentKey);
                    throw new InvalidOperationException(msg);
                }

                parentNode.IsExpanded = true;
                items = parentNode.Items;
            }

            //all ancestor nodes are expanded - now select the node
            TreeViewItem itemNode = TryFindItemNode(items, itemKey, false);

            if (itemNode == null)
            {
                //this could be the case if we received a root item, but the
                //tree's Items collection does not contain it.
                string msg = "Cannot select item '{0}' - the item does not exist in the hierarchy of the tree's bound items.";
                msg = String.Format(msg, itemKey);
                throw new InvalidOperationException(msg);
            }

            itemNode.IsSelected = true;
            itemNode.BringIntoView();
        }
 public void SelectItemNamed(string name)
 {
     foreach (object o in objectTree.Items)
     {
         if (o is TypeInfo)
         {
             if (((TypeInfo)o).Name.ToLower().Equals(name.ToLower()))
             {
                 TreeViewItem titem = ((TreeViewItem)objectTree.ItemContainerGenerator.ContainerFromItem(o));
                 if (titem != null)
                 {
                     titem.BringIntoView();
                     titem.IsSelected = true;
                     return;
                 }
             }
         }
         else if (o is PropInfo)
         {
             if (((PropInfo)o).Name.ToLower().Equals(name.ToLower()))
             {
                 TreeViewItem titem = ((TreeViewItem)objectTree.ItemContainerGenerator.ContainerFromItem(o));
                 if (titem != null)
                 {
                     titem.BringIntoView();
                     titem.IsSelected = true;
                     return;
                 }
             }
         }
         else if (o is FunctionInfo)
         {
             if (((FunctionInfo)o).Name.ToLower().Equals(name.ToLower()))
             {
                 TreeViewItem titem = ((TreeViewItem)objectTree.ItemContainerGenerator.ContainerFromItem(o));
                 if (titem != null)
                 {
                     titem.BringIntoView();
                     titem.IsSelected = true;
                     return;
                 }
             }
         }
     }
 }
        private void selectChannel(int channelId)
        {
            foreach (GroupDTO group in tvGroups.Items)
            {
                TreeViewItem groupItem = tvGroups.ItemContainerGenerator.ContainerFromItem(group) as TreeViewItem;
                groupItem.BringIntoView();

                foreach (ChannelDTO channel in groupItem.Items)
                {
                    if (channel.Id == channelId)
                    {
                        TreeViewItem channelItem = groupItem.ItemContainerGenerator.ContainerFromItem(channel) as TreeViewItem;
                        channelItem.Focus();
                        return;
                    }
                }
            }
        }
        /// <summary>
        /// 选中itemsControl下的item节点
        /// </summary>
        /// <param name="itemsControl"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        private bool SelectTreeViewItem(ItemsControl itemsControl, object item)
        {
            if (itemsControl.ItemsSource == null)
            {
                return(false);
            }
            if (m_founded)
            {
                return(true);
            }
            TreeViewItem currentTreeViewItem = (TreeViewItem)itemsControl.ItemContainerGenerator.ContainerFromItem(item);

            if (currentTreeViewItem != null)
            {
                m_founded = true;
                //(m_container as TreeView).CollapseAll();//折叠因查找item而展开的所有项
                currentTreeViewItem.BringIntoView();
                return(true);
            }

            foreach (object treeItem in itemsControl.ItemsSource)
            {
                currentTreeViewItem = (TreeViewItem)itemsControl.ItemContainerGenerator.ContainerFromItem(treeItem);
                if (currentTreeViewItem == null)//未显示的项的TreeViewItem为null
                {
                    continue;
                }
                if (currentTreeViewItem.ItemsSource == null)
                {
                    continue;
                }
                currentTreeViewItem.IsExpanded = true;//展开
                WaitForPriority(DispatcherPriority.Background);
                ItemContainerGenerator itemContainerGenerator = currentTreeViewItem.ItemContainerGenerator;
                if (itemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
                {
                    if (SelectTreeViewItem(currentTreeViewItem, item))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemple #13
0
        static void OnBringIntoViewWhenSelectedChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
        {
            TreeViewItem item = depObj as TreeViewItem;

            if (item == null)
            {
                return;
            }

            if (e.NewValue is bool == false)
            {
                return;
            }

            if ((bool)e.NewValue)
            {
                item.BringIntoView();
            }
        }
Exemple #14
0
        private void DataGridMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DataGridRow row = MainWindow.GetParent <DataGridRow>((DependencyObject)e.OriginalSource);

            if (row != null)
            {
                DataGrid       dataGrid = (DataGrid)sender;
                FileSystemItem item     = (FileSystemItem)dataGrid.SelectedItem;

                if (item is Folder)
                {
                    _selectedTreeViewItem.IsExpanded = true;
                    _selectedTreeViewItem.UpdateLayout();
                    _selectedTreeViewItem            = (TreeViewItem)_selectedTreeViewItem.ItemContainerGenerator.ContainerFromItem(item);
                    _selectedTreeViewItem.IsSelected = true;
                    _selectedTreeViewItem.BringIntoView();
                }
            }
        }
        private static bool SelectItem(object o, TreeViewItem parentItem)
        {
            if (parentItem == null)
            {
                return(false);
            }

            bool isExpanded = parentItem.IsExpanded;

            if (!isExpanded)
            {
                parentItem.IsExpanded = true;
                parentItem.UpdateLayout();
            }

            TreeViewItem item = parentItem.ItemContainerGenerator.ContainerFromItem(o) as TreeViewItem;

            if (item != null)
            {
                item.IsSelected = true;
                item.BringIntoView(new Rect(new Size(50, 100)));
                return(true);
            }


            bool wasFound = false;

            for (int i = 0; i < parentItem.Items.Count; i++)
            {
                TreeViewItem itm   = parentItem.ItemContainerGenerator.ContainerFromIndex(i) as TreeViewItem;
                var          found = SelectItem(o, itm);
                if (!found)
                {
                    itm.IsExpanded = false;
                }
                else
                {
                    wasFound = true;
                }
            }

            return(wasFound);
        }
        /// <summary>
        /// Selects the first node in the tree view returns true if the
        /// selection was successful or false if this needs to be called
        /// again when the base.ItemContainerGenerator.StatusChanged event
        /// is fired. Note if false is returned the same items control (which
        /// will be modified as it'a a ref) needs to be passed in next time
        /// to complete the selection.
        /// </summary>
        /// <returns></returns>
        internal static bool SelectItemByPath(ref ItemsControl itemsControl, IList itemToSelectByPath)
        {
            IList source = itemsControl.ItemsSource as IList;

            if (source == null || itemToSelectByPath.Count < 1)
            {
                itemToSelectByPath.Clear();
                return(true);
            }
            if (!source.Contains(itemToSelectByPath[0]))
            {
                itemToSelectByPath.Clear();
                return(true);
            }

            if (itemsControl.HasItems)
            {
                // Check that the items container generator has been started.
                // If so then just select the item, if not then return false;

                TreeViewItem item = itemsControl.ItemContainerGenerator.ContainerFromItem(itemToSelectByPath[0]) as TreeViewItem;
                if (item != null)
                {
                    if (itemToSelectByPath.Count == 1)
                    {
                        itemToSelectByPath.RemoveAt(0);
                        item.IsSelected = true;
                        item.BringIntoView();
                        return(true);
                    }
                    else
                    {
                        itemToSelectByPath.RemoveAt(0);
                        item.IsExpanded = true;
                        itemsControl    = item;
                        return(SelectItemByPath(ref itemsControl, itemToSelectByPath));
                    }
                }
            }
            return(false);
        }
        private static bool ShowSelectedThing(ItemsControl parentContainer, GitComment objectToFind)
        {
            if (objectToFind == null)
            {
                return(false);
            }

            // check current level of tree
            foreach (ICommentTree item in parentContainer.Items)
            {
                TreeViewItem currentContainer = (TreeViewItem)parentContainer.ItemContainerGenerator.ContainerFromItem(item);
                if ((currentContainer != null) && (item.Comment.Id == objectToFind.Id))
                {
                    currentContainer.BringIntoView();
                    return(true);
                }
            }
            // item is not found at current level, check the kids
            foreach (ICommentTree item in parentContainer.Items)
            {
                TreeViewItem currentContainer = (TreeViewItem)parentContainer.ItemContainerGenerator.ContainerFromItem(item);
                if ((currentContainer != null) && (currentContainer.Items.Count > 0))
                {
                    // Have to expand the currentContainer or you can't look at the children
                    currentContainer.IsExpanded = true;
                    currentContainer.UpdateLayout();
                    if (!ShowSelectedThing(currentContainer, objectToFind))
                    {
                        // Haven't found the thing, so collapse it back
                        currentContainer.IsExpanded = false;
                    }
                    else
                    {
                        // We found the thing
                        return(true);
                    }
                }
            }
            // default
            return(false);
        }
        private void TreeViewElem_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e)
        {
            // Alternative (1): not working completely properly
#if __not_working_completely_properly
            Alternative 1
            base.BringIntoView();
            var scrollViewer = treeViewInner.Template.FindName("_tv_scrollviewer_", treeViewInner) as ScrollViewer;
            if (scrollViewer != null)
            {
                Dispatcher.BeginInvoke(
                    System.Windows.Threading.DispatcherPriority.Loaded,
                    (Action)(() => scrollViewer.ScrollToLeftEnd()));
            }
            * /
#endif

            // Alternative (2): seems working fine

            // Ignore re-entrant calls
            if (mSuppressRequestBringIntoView)
            {
                return;
            }

            // Cancel the current scroll attempt
            e.Handled = true;

            // Call BringIntoView using a rectangle that extends into "negative space" to the left of our
            // actual control. This allows the vertical scrolling behaviour to operate without adversely
            // affecting the current horizontal scroll position.
            mSuppressRequestBringIntoView = true;

            TreeViewItem tvi = sender as TreeViewItem;
            if (tvi != null)
            {
                Rect newTargetRect = new Rect(-1000, 0, tvi.ActualWidth + 1000, tvi.ActualHeight);
                tvi.BringIntoView(newTargetRect);
            }

            mSuppressRequestBringIntoView = false;
        }
Exemple #19
0
 public void FindTextInTree(string text, int searchType)
 {
     if (!((MainViewModel)DataContext).FindText(text, searchType))
     {
         MessageBox.Show("Search text not found.", "No Matches", MessageBoxButton.OK, MessageBoxImage.Information);
     }
     else if (((MainViewModel)DataContext).CurrentIdeaNote != null)
     {
         Application.Current.MainWindow.Activate();
         Stack <IdeaNote> stack = ((MainViewModel)DataContext).CurrentIdeaNote.GetRootToChildStack();
         TreeViewItem     item  = GetTreeViewItemFromIdeaNote(noteTreeView, stack);
         if (item != null)
         {
             item.BringIntoView();
             if (((MainViewModel)DataContext).CurrentIdeaNote.IdeaNoteType == nameof(TextNote))
             {
                 FindText(text, 0, false);
             }
         }
     }
 }
 private void RunningMapTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs <object> e)
 {
     try {
         if (sender == e.OriginalSource && e.NewValue != null && !object.ReferenceEquals(e.OldValue, e.NewValue))
         {
             CircuitMap map = e.NewValue as CircuitMap;
             if (map != null)
             {
                 TreeViewItem item = this.Container((TreeView)sender, map);
                 if (item != null)
                 {
                     item.IsExpanded = true;
                     item.BringIntoView();
                 }
             }
         }
     } catch (Exception exception) {
         Tracer.Report("MainFrame.RunningMapTreeViewSelectedItemChanged", exception);
         this.ReportException(exception);
     }
 }
Exemple #21
0
        void JumpToNode(TreeViewItem tvi, string NodeName)
        {
            if (tvi.Tag.ToString() == NodeName)
            {
                tvi.IsExpanded = true;
                tvi.BringIntoView();
                return;
            }
            else
            {
                tvi.IsExpanded = false;
            }

            if (tvi.HasItems)
            {
                foreach (var item in tvi.Items)
                {
                    TreeViewItem temp = item as TreeViewItem;
                    JumpToNode(temp, NodeName);
                }
            }
        }
Exemple #22
0
            public void ExpandNext()
            {
continueWithNextItem:

                var item = _items[_next];

                _next++;

                var childNode = _parentGenerator.ContainerFromItem(item) as TreeViewItem;

                if (childNode != null)
                {
                    var generator = childNode.ItemContainerGenerator;
                    _parentGenerator = generator;
                    _lastItem        = childNode;

                    if (_next >= _items.Length)
                    {
                        _lastItem.IsSelected = true;
                        _lastItem.BringIntoView();

                        if (_expandLastItem)
                        {
                            _lastItem.IsExpanded = true;
                        }

                        return;
                    }

                    if (generator.Status == GeneratorStatus.ContainersGenerated)
                    {
                        childNode.IsExpanded = true;
                        goto continueWithNextItem;
                    }

                    generator.StatusChanged += ItemContainerGeneratorStatusChanged;
                    childNode.IsExpanded     = true;
                }
            }
Exemple #23
0
        private void NewCustomItem_Click(object sender, RoutedEventArgs e)
        {
            SlotType slot = SlotType.None;

            if (tvItems.SelectedItem != null)
            {
                slot = (SlotType)(tvItems.SelectedItem as TreeViewItem).Tag;
            }
            else
            {
                if (!GetSlot(SlotType.None, null, out slot))
                {
                    return;
                }
            }

            if (slot == SlotType.None)
            {
                return;
            }

            CustomItemContainer cic = new CustomItemContainer {
                Name = "<Custom Item>"
            };

            cic.Item = new DDOItemData(ItemDataSource.Custom, false)
            {
                Name = cic.Name, Slot = slot
            };
            cic.Item.AddProperty("Minimum Level", null, 1, null);
            AddSlotSpecificProperties(cic.Item);

            CustomItemsManager.CustomItems.Add(cic);
            TreeViewItem tvi = AddItemToTreeView(cic);

            tvi.BringIntoView();
            tvi.IsSelected = true;
        }
Exemple #24
0
        /// <summary>
        /// Get the TreeViewItems (containers) and let the InspectorTreeNodes
        /// know where they are.
        /// </summary>
        void ItemContainerGenerator1_StatusChanged(object sender, EventArgs e)
        {
            if (Window.TreeView1.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
            {
                foreach (var obj in Window.TreeView1.Items)
                {
                    InspectorNode o = (InspectorNode)obj;
                    if (o.UIContainer == null || (o.UIContainer != null && o.UIContainer.Header != null && o.UIContainer.Header.ToString().Equals("{DisconnectedItem}")))
                    {
                        TreeViewItem item = Window.TreeView1.ItemContainerGenerator.ContainerFromItem(o) as TreeViewItem;
                        o.UIContainer = item;

                        // If we're in the Modified only view, expand everything.
                        if (Config.ModifiedOnly && o.UIContainer != null)
                        {
                            o.UIContainer.IsExpanded = true;
                        }


                        // If this item didn't have a UIContainer is because it
                        // is new, expand it. TODO: This line used to expand every
                        // root node, but it makes the inspector really slow to appear.
                        // This should be configurable.
                        //o.Expand();
                        // item could be null if we're filtering the collection (there's an item but is not being show).
                        if (InspectedObjects.Count > 2 && item != null)
                        {
                            if (o.AutoExpand)
                            {
                                ((TreeViewItem)o.UIContainer).IsExpanded = true;
                            }
                            item.IsSelected = true;
                            item.BringIntoView();
                        }
                    }
                }
            }
        }
Exemple #25
0
        internal VideoFile SelectFile(string fileName)
        {
            VideoFile v = null;

            foreach (VideoGroup group in treeFiles.Items)
            {
                var tvi = treeFiles.ItemContainerGenerator.ContainerFromItem(group) as TreeViewItem;
                foreach (VideoFile videoFile in tvi.Items)
                {
                    TreeViewItem childItem = tvi.ItemContainerGenerator.ContainerFromItem(videoFile) as TreeViewItem;
                    if (childItem != null)
                    {
                        childItem.IsSelected = (string.Compare(fileName, videoFile.FileName, true) == 0);
                        if (childItem.IsSelected)
                        {
                            v = videoFile;
                            childItem.BringIntoView();
                        }
                    }
                }
            }
            return(v);
        }
        static void OnTreeViewItemSelected(object sender, RoutedEventArgs e)
        {
            // Only react to the Selected event raised by the TreeViewItem
            // whose IsSelected property was modified.  Ignore all ancestors
            // who are merely reporting that a descendant's Selected fired.

            if (!Object.ReferenceEquals(sender, e.OriginalSource))
            {
                return;
            }

            TreeViewItem  item   = e.OriginalSource as TreeViewItem;
            ViewModelMain vmMain = ServiceLocator.Current.GetInstance <ViewModelMain>();

            //SideMenuVM sideMenuVM = sender as SideMenuVM;

            //Debug.WriteLine("ccccccccccccccccccccccccccccccccccccccccccccccccccc. node index == " + sideMenuVM.Index.ToString());
            Debug.WriteLine("ccccccccccccccccccccccccccccccccccccccccccccccccccc. sender == " + sender.ToString());
            if (item != null)
            {
                item.BringIntoView();
            }
        }
        /*
         * 将新添加的页面加入到页面树中
         */
        private void insertToTree(ItemsControl itemsControl, StorageImageFolder folder)
        {
            foreach (TreeViewItem item in itemsControl.Items)
            {
                Int32 folderId = (Int32)item.Tag;
                if (parentId == folderId)
                {
                    TreeViewItem newItem = new TreeViewItem();
                    newItem.Header  = folder.name;
                    newItem.Tag     = folder.id;
                    newItem.Padding = new Thickness(5);
                    // newItem.Foreground = Brushes.White;

                    item.Items.Add(newItem);
                    newItem.BringIntoView();
                    break;
                }
                else
                {
                    insertToTree(item, folder);
                }
            }
        }
        //15Jan2015
        private bool BringLastVisibleLeafIntoView(TreeViewItem t)
        {
            bool found = false;

            if (t.Tag == null && t.Items.Count > 0)// non leaf node
            {
                int childcount       = t.Items.Count;
                int indexoflastchild = childcount - 1;//zero based index
                do
                {
                    if (indexoflastchild >= 0)
                    {
                        found = BringLastVisibleLeafIntoView(t.Items.GetItemAt(indexoflastchild) as TreeViewItem);
                        indexoflastchild--;
                    }
                    else
                    {
                        break;
                    }
                } while (!found);
            }
            else //leaf node
            {
                if ((t.Tag as IAUControl).BSkyControlVisibility == System.Windows.Visibility.Visible)//leaf is set to visible
                {
                    (t.Tag as FrameworkElement).BringIntoView();
                    t.BringIntoView(); //scroll left tree to latest item in tree.(deepest child node at lowest level)
                    found = true;      //leaf found and set for scroll into view.
                }
                else
                {
                    found = false;
                    return(found);
                }
            }
            return(found);
        }
        /// <summary>
        /// Attempts to select a specific node in a TreeView, by recursively drilling down to the item indicated by the specified
        /// trail.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="trail">The trail.</param>
        /// <param name="index">The index.</param>
        public static void SelectItem(ItemsControl control, IList trail, int index)
        {
            object currentItem = trail[index];

            // If the control has not generated it's containers, then we need to delay our call until it does.
            if (control.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
            {
                // Find the current item in the control's Items
                foreach (object item in control.Items)
                {
                    if (item == currentItem)
                    {
                        TreeViewItem container = (TreeViewItem)control.ItemContainerGenerator.ContainerFromItem(item);
                        if (++index < trail.Count)
                        {
                            // We have more items to drill down into, so use a recursive call with a new control and index
                            container.IsExpanded = true;
                            SelectItem(container, trail, index);
                        }
                        else
                        {
                            // We found the item, so select it and bring it into view
                            container.IsSelected = true;
                            container.BringIntoView();
                        }
                        break;
                    }
                }
            }
            else
            {
                control.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, (DispatcherOperationCallback) delegate(object arg) {
                    SelectItem(control, trail, index);
                    return(null);
                }, null);
            }
        }
        public bool TrySelectTreeNode(object correspondingUIElementInUserApplication)
        {
            bool wasFullyExpanded = _hasBeenFullyExpanded;

            // First, we need to expand all the nodes so that the "item generators" can be called (which creates the TreeViewItems") and so we can select the node:
            ExpandAllNodes();

            // Then, select the item:
            foreach (Tuple <TreeNode, TreeViewItem> treeNodeAndTreeViewItem in TraverseTreeViewItems(TreeViewForXamlInspection))
            {
                TreeNode     treeNode     = treeNodeAndTreeViewItem.Item1;
                TreeViewItem treeViewItem = treeNodeAndTreeViewItem.Item2;
                if (treeNodeAndTreeViewItem.Item1.Element == correspondingUIElementInUserApplication)
                {
                    if (treeViewItem != null)
                    {
                        Dispatcher.BeginInvoke((Action)(async() =>
                        {
                            treeViewItem.IsSelected = true;

                            if (!wasFullyExpanded)
                            {
                                await Task.Delay(3000);     // We give the time to the TreeView to expand, in ordero to make it possible to bring the selected item into view.
                            }
                            treeViewItem.BringIntoView();
                        }));
                    }
                    else
                    {
                        throw new Exception("Unable to get the TreeViewItem from the TreeNode. Please inform the authors at: [email protected]");
                    }
                    return(true);
                }
            }
            return(false);
        }