Is there a nice way (except retemplating the whole TreeViewItem.Template
) to disable selection in TreeView
?
I am basically looking for the ItemsControl
style of the TreeView
(An ItemsControl
is the best use to 'disable' selection on ListBox
, read this post)
I did this a differently than the accepted answer:
Lets say that you have a property in your ViewModel (say 'ShouldPreventSelection') Now when ShouldPreventSelection is true you want selection to be disabled:
In your TreeView fire the PreviewSelected event like so:
Then in the codebehind you can the following:
Whenever an item is selected, you could "unselect" it. Ex. modify the code from http://www.codeproject.com/KB/WPF/TreeView_SelectionWPF.aspx or use a MVVM approach (see http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx) and always set IsSelected back to false.
Try this:
I just unselected the TreeViewItems as they get selected. I Use the TreeView only once. However if i added several placed I would consider looking into adding this to a Attacked Behavior.
Xaml:
Code behind:
Based off of the links to the currently accepted answer, I implemented this in my project:
Works for TreeViewItem as well. And in the view model:
Now you don't have to go hunting!
This did the trick for me (based on this answer, but no tied to item - selection is disabled whatsoever):