Steve Brouillard
Steve Brouillard

Reputation: 3266

Silverlight 3 - Accessing TreeView Item's parent object

I'm using a TreeView along with a HierarchicalDataTemplate to display a Hierarchical listing returned from a webservice. Depending on search criteria, this listing can get to be very long and several nested levels deep. It would be useful to display a "map" of sorts to the user so that they can see where in this listing they are relative to the top level. The model used to create the hierarchy looks like this:

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 a 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's ItemsSource would be bound to the ObservableCollection of IndexEntry types. I don't see any obvious way to access the parent object as things are now. I am considering the option of adding another property in the model that would point directly to the parent object of that particular entry. This would ultimately allow me to walk up & down the hierarchy and grab what I like as I need it.

So, the question is - Can anyone think of a better way to accomplish this? Is there a property in the TreeView itself that I'm missing that will provide this ability?

Upvotes: 0

Views: 3976

Answers (2)

Shawn Oster
Shawn Oster

Reputation: 151

There is an easy solution in the July 2009 release of the Silverlight Toolkit, the GetParentItem extension method in TreeViewExtensions.

  1. Download and install the Silverlight Toolkit.

  2. Add a reference to System.Windows.Controls.Toolkit (which can be found in C:\Program Files (x86)\Microsoft SDKs\Silverlight\v3.0\Toolkit\Jul09\Bin).

  3. From the method you want to get the parent (I'm going to use the SelectedItemChanged event by way of 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 quite a few great extensions hiding in there that I'd encourage you to explore for setting the selected item, expanding nodes and getting the containers of items.

Upvotes: 1

Paully
Paully

Reputation: 570

TreeViewExtensions works for me to find the treeviewitem and parent object. View the bottom page for final.

http://silverlight.net/forums/t/65277.aspx

Upvotes: 0

Related Questions