How to bind to SelectedItem property of WPF TreeView?

Rachael picture Rachael · Mar 7, 2013 · Viewed 13.4k times · Source

I have adapted the TreeView Control sample project here for use with Entity Framework objects. It works beautifully, but like many others attempting to update collections or properties on their ParentViewModels based SelectedItem changes, I too am unable to bridge the gap of understanding.

I am working in MVVM, and want my code-behind free of any mess. As a beginner, I like the cleanliness of implementing PropertyChanged notifications but since their is no inherent "SelectedItem" property to bind to on the TreeView, I am unable to raise my PropertyChanged event as I normally would with ListBox.

I too have a SelectedItem property (that actually successfully captures the object where isSelected = true) on my ChildViewModel (see H.B.'s answer to this question). I also have a SelectedItem of type ChildViewModel on my ParentViewModel which is bound to my View (see @Martin Liversage's post here). I cannot get them to sync up.

Please help me understand how to communicate the SelectedItem property of my ChildViewModel to my ParentViewModel. I do not bind my TreeView to a CollectionView, so I am unable to get the CurrentItem in the view collection.

My viewmodel collections I'm dealing with are very query-heavy, so I've not included any code for now. Please let me know what is needed for clarity.

Answer

Marc picture Marc · Mar 7, 2013

So, at least you're starting to get used to your daily MVVM-WTF... 'Why do I have to post on SO for stuff as basic as this'. One day, you'll love MVVM, I promise ;)

That being said: As you know, the TreeView doesn't support synchronizing the SelectedItem property. It does exist, though, but it is readonly. What you want to do, is to extend the behavior of the TreeView to synchronize it's selected item with a property on it's ViewModel.

This problem description points you in the right direction: Behaviors. Behaviors (or, to be precise, System.Windows.Interactivity.Behavior<>s) allow you to extend the functionality of any DependencyObject. (Good introduction)

An approach to synchronize your TreeView with a selected item via behaviors, can be found here:

SO Thread

This should do for you already. You can just copy and paste the code of Steve GreatRex and go for it. Please comment, if you need help with the approach. Have fun learning!