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'll also need the Silverlight 4 SDK for the TreeView, which only comes from the SDK.

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 readonly property.

In silverlight, you don't even have OneWayToSource, so binding two way to SelectedItem (which does exist in XAML, even if intelisense 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 it's 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: