Home > WPF, WPF Controls, WPF TreeView > Preventing WPF TreeView items from being selected

Preventing WPF TreeView items from being selected

March 6th, 2008

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>

 

tree_dialogikWith 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.


Author: Categories: WPF, WPF Controls, WPF TreeView Tags: ,
  1. LorenLiu
    January 12th, 2012 at 03:12 | #1

    Hi,

    I have tried to set the focusable to false, the parent node is not selectable, but if I have one child item selected and then collapse the parent item, the parent will be selected, how can I make the parent not selected in this scenario?

    Thank you very much,
    -Loren

  1. May 4th, 2008 at 22:20 | #1