Silverlight 3 - Accessing the Parent Item TreeView
I am using a TreeView along with HierarchicalDataTemplate to display the hierarchical listing returned from a web service. Depending on the search criteria, this list can be very long, and several nested levels can be deep. It would be helpful to show the user a "map" so they can see where in this list they belong to the top level. The model used to create the hierarchy is as follows:
public class IndexEntry
{
public int Score { get; set; }
//More properties that define attributes of this class
//Child objects of the hierarchy are stored in this property
public List<IndexEntry> SubEntries { get; set; }
}
As you can see, the hierarchy is built using the List of IndexEntry types.
The ViewModel looks like this:
public class IndexEntriesViewModel
{
//TreeView ItemsSource is bound to this collection
public ObservableCollection<IndexEntry> IndexList { get; set; }
//More properties to define the ViewModel
}
As you can see, the TreeView ItemsSource is bound to ObservableCollection types of IndexEntry types. I don't see an obvious way to access the parent object as it is now. I am considering adding another property to the model that will point directly to the parent of this particular record. This would ultimately allow me to climb up and down the hierarchy and grab what I like when I need it.
So the question is, can anyone think of a better way to achieve this? Is there a property on the TreeView that I am missing that will provide this ability?
a source to share
In the Silverlight Toolkit release, the GetParentItem extension method in TreeViewExtensions has a simple solution.
-
Download and install the Silverlight Toolkit .
-
Add a link to System.Windows.Controls.Toolkit (which can be found at C: \ Program Files (x86) \ Microsoft SDK \ Silverlight \ v3.0 \ Toolkit \ Jul09 \ Bin).
-
From the method you want from the parent (I will use the SelectedItemChanged event as an example):
private void OrgTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { if (e.NewValue != null) { var parent = ((TreeView)sender).GetParentItem(e.NewValue); if (parent != null) { Status.Text = "Parent is " + parent.ToString(); } }; }
There are many great extensions that I would encourage you to explore for setting a selected item, expanding nodes, and getting item containers.
a source to share