Preventing WPF TreeView items from being selected
If you have a WPF TreeView control that shows nested data, and you don’t want the user to select nodes that contain child nodes, you can solve this declaratively as TreeViewItem provides all we need:
- HasItems dependency property (bool)
- Focusable dependency property (bool)
As both properties have the same type, you can use a binding expression (needs inversion of the boolean), or just use a trigger. Here’s the trigger:
<!-- root items can only be expanded, not selected --> <Trigger Property="HasItems" Value="true"> <Setter Property="Focusable" Value="false" /> </Trigger>
With this trigger in place, simply clicking on a node that contains child items does not change the tree’s current selection, while expanding/collapsing still works.
A common scenario for such a behavior is a tree that contains nodes which are used for grouping purposes only as in the example screenshot.