Table of Contents



Introduction

This sample shows how to two-way-bind to the SelectedItem property of a WPF or Silverlight TreeView.

It also shows how to expand nodes down to the selected item, and collapse all other nodes (to keep it tidy).

 

 

Building the Sample

Just download, unzip, open and run!

You will also need the Silverlight 4 SDK for the TreeView, or the Silverlight 5 SDK if you wish to work on your own Silverlight 5 project.
The TreeView is not in the standard Silverlight framework. Remember to add an xmlns reference to the SDK if you wish to use this in your own project.

If you use a previous version of the SDK, just change the reference in the project.

 

Description

 
The problem with the TreeView is that the SelectedItem is a read-only property.

In Silverlight, you don't even have OneWayToSource, so binding two way to SelectedItem (which does exist in XAML, even if IntelliSense doesn't show it) causes binding errors.

The solution is to add an Attached Property, which

1) Taps into the SelectedItemChanged event for target->source

2) Searches down the TreeViewItems for the object to select, for source->target.

In the process of searching down for the selected item, it has to expand the parent node to get its children.

If it isn't in any of the descendants for a node, then the node gets closed again.

Behind all this is the following class: