/// <summary> /// Expands one path in the tree and selects a particular TreeViewItem. /// </summary> /// <param name="sender">The Button clicked.</param> /// <param name="e">Parameters associated to the Button click.</param> private void SelectOne(object sender, RoutedEventArgs e) { ObjectCollection treeOfLifeCollection = (ObjectCollection)this.Resources["treeOfLife"]; TaxonomyViewModel elementToExpand = (TaxonomyViewModel)((TaxonomyViewModel)treeOfLifeCollection[2]).Subclasses[3].Subclasses[0].Subclasses[0].Subclasses[0]; // This iterates through the three top-level items only. foreach (TaxonomyViewModel item in treeView.Items) { if (item.ExpandSuperclasses(elementToExpand)) { elementToExpand.IsSelected = true; break; } } }
/// <summary> /// This helper method traverses the tree in a depth-first non-recursive way /// and executes the action passed as a parameter on each item. /// </summary> /// <param name="itemAction">Action to be executed for each item.</param> private void ApplyActionToAllItems(Action <TaxonomyViewModel> itemAction) { Stack <TaxonomyViewModel> dataItemStack = new Stack <TaxonomyViewModel>(); dataItemStack.Push(this); while (dataItemStack.Count != 0) { TaxonomyViewModel currentItem = dataItemStack.Pop(); itemAction(currentItem); foreach (TaxonomyViewModel childItem in currentItem.Subclasses) { dataItemStack.Push(childItem); } } }
/// <summary> /// This helper method uses recursion to look for the element passed as a parameter in the view model /// hierarchy and executes the action passed as a parameter to its entire ancestor chain (excluding /// the item itself). /// </summary> /// <param name="itemToLookFor">The element this method will look for.</param> /// <param name="itemAction">Action to be executed on each superclass in the ancestor chain.</param> /// <returns>True if it the itemToLookFor was found, false otherwise.</returns> private bool ApplyActionToSuperclasses(TaxonomyViewModel itemToLookFor, Action <TaxonomyViewModel> itemAction) { if (itemToLookFor == this) { return(true); } else { foreach (TaxonomyViewModel subclass in this.Subclasses) { bool foundItem = subclass.ApplyActionToSuperclasses(itemToLookFor, itemAction); if (foundItem) { itemAction(this); return(true); } } return(false); } }
/// <summary> /// This method sets IsExpanded to true for each element in the ancestor chain of the item /// passed as a parameter. /// </summary> /// <param name="itemToLookFor">The element this method will look for.</param> /// <returns>True if it the itemToLookFor was found, false otherwise.</returns> public bool ExpandSuperclasses(TaxonomyViewModel itemToLookFor) { return(ApplyActionToSuperclasses(itemToLookFor, superclass => superclass.IsExpanded = true)); }