I have a ViewModel on top of a WPF TreeView control. I want the ViewModel to be able to set and read the SelectedItem from the TreeView. However, the SelectedItem property of the TreeView is not bindable.
I am able to set and get the selected item in the code behind (using the ItemContainerGenerator and TreeViewItem.IsSelected = true) but this leads to some ugly communication between the code behind and the ViewModel.
Does anyone have a clean solution for this?
Best Answer
I can provide an example. What I do is setting the
IsSelected
property of aTreeViewItem
(not theTreeView
itself) in the view model, because you can bind to this.In my view model I have a property
ElementInViewModel
which is a data structure that forms a tree itself. I use aHierarchicalDataTemplate
in my Xaml to display it. The data object itself is of typeYourDomainType
and its child elements (of the same type) are in itsChildElements
property.In the view model, I set the
IsExpanded
andIsSelected
property of my data classYourDomainType
. Because of the style defined below, they will pass this setting to theTreeViewItem
.Does this work for you?