Setting the SelectedItem in a Silverlight TreeView

I wanted to select a specific item in my Silverlight TreeView programatically.  Looking at the TreeView.SelectedItem property the setter is not public so it cannot be done this way.

If you are simply adding TreeViewItems to the TreeView you can cast the item you want to select in the Items collection to a TreeViewItem and set the IsSelected property to true. The following example will grab the first item and set it to selected.

TreeViewItem item = tvDirectories.Items[0] as TreeViewItem;
item.IsSelected = true;

If you are binding a list of business objects to the TreeView this will not work as the Items collection will be a list of your object.  In this scenario you can use the ItemContainerGenerator property of the TreeView to get the underlying TreeViewItem.  In this example I have a collection of Gallery objects bound to my TreeView and am using the ContainerFromIndex method to get the TreeViewItem at position 0.

TreeViewItem item = tvDirectories.ItemContainerGenerator.ContainerFromIndex(0) as TreeViewItem;
item.IsSelected = true;

The ItemContainerGenerator class also has a ContainerFromItem method that will get the TreeViewItem by passing it an instance of the business object you want to select.

Gallery gallery = GetGallery(); //Some method that gets the object you want to select in the TreeView
TreeViewItem item = tvDirectories.ItemContainerGenerator.ContainerFromItem(gallery) as TreeViewItem;
item.IsSelected = true;

In my application I want to select the TreeViewItem based on the ServerPath of the Gallery object so I’m using some of the nifty Linq extension methods (Cast and Single) to get my business object.

public void SelectGallery(string serverPath)
{
    Gallery gallery = tvDirectories.Items.Cast<gallery>().Single(x => x.ServerPath.Equals(serverPath));
           
    if (gallery != null)
    {
        TreeViewItem item = tvDirectories.ItemContainerGenerator.ContainerFromItem(gallery) as TreeViewItem;
        item.IsSelected = true;
    }
}
Posted on by Joe in Silverlight

One Response to Setting the SelectedItem in a Silverlight TreeView

  1. Peter Jorgensen

    Hi Joe,
    This info saved my day :-)
    Especially the “ItemContainerGenerator” was exactly what did the trick.
    Thanks.

    Peter

Add a Comment