WPF TreeView – SelectedItem Two Way Binding

wpf treeview

Because the standard WPF TreeView implementation supports Virtualization it is unable to support two way bindings on its SelectedItem property as standard. This makes sense, because with Virtualization you may not have a container (TreeViewItem) available for any particular bound data item at the time you need it (to set its IsSelected property of the TreeViewItem to ‘True’).
The solution is to use attached properties to force the ItemContainerGenerator to create the necessary containers for each data item. This will break the virtualization support, but that is a price you need to pay for a solution to this issue, so you should only use it on TreeView controls where the lack of Virtualization wont be a significant drawback.
Here is the attached property implementation:

And here is the attached property in action.

Here’s the code-behind for the demo XAML

About the author

Dean Chalk

I am a freelance (contract) Microsoft WPF developer, specialising in challenging, high-performance user interface development. I have been working exclusively on enterprise WPF app development since 2006, and I have been a part of some of the most demanding WPF projects ever created withing the Investment Banking / trading industry.


>