Execute command when any TreeViewItem is expanded

Sep 14, 2009 at 12:12 PM


So I created a Behavior attached to the Expanded event of the TreeViewItem class and I also have the ICommand implemented in the ViewModel.

The question is: Where and how can I specify the behavior and the ICommand binding in the XAML? The command is to be executed when any tree view item is expanded.


Sep 21, 2009 at 2:28 PM


The first thing you will have to do is create a template for the TreeViewItems that sets the AttachedBehavior for each TreeViewItem created in the TreeView. Assuming you are using Silverlight 3 (based on your history of asked/answered questions), there is no way of doing the binding to the command through XAML (as there is not RelativeSource property for binding other than Self) since the DataContext of the TreeViewItem is the DataSource of the TreeView.

A possible workaround could be having a StaticResource in your XAML, and instead of binding directly to the Command in the TreeViewTemplate, bind to the StaticResource. In the View's code behind, you can bind the Resource to the command in the ViewModel.

The Prism-v2 Silverlight RI, uses a similar approach (with an ObservableCommand) in the PositionSummaryView and ViewModel to bind to a command in a different data context. You might find it useful.

Please let me know if this helps.

Damian Schenkelman