Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable WPF TreeView (or TreeViewItem) selection?

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)

like image 971
Shimmy Weitzhandler Avatar asked Dec 29 '10 12:12

Shimmy Weitzhandler


4 Answers

Try this:

<Trigger Property="HasItems" Value="true">
   <Setter Property="Focusable" Value="false" />
</Trigger>
like image 192
Morten Strand Avatar answered Nov 04 '22 05:11

Morten Strand


This did the trick for me (based on this answer, but no tied to item - selection is disabled whatsoever):

<TreeView>
  <TreeView.ItemContainerStyle>
    <Style TargetType="TreeViewItem">
      <Setter Property="Focusable" Value="False" />
    </Style>
  </TreeView.ItemContainerStyle>
</TreeView>
like image 41
Shimmy Weitzhandler Avatar answered Nov 04 '22 05:11

Shimmy Weitzhandler


Based off of the links to the currently accepted answer, I implemented this in my project:

<ListView.ItemContainerStyle>
    <Style TargetType="{x:Type ListViewItem}">
        <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
    </Style>
</ListView.ItemContainerStyle>

Works for TreeViewItem as well. And in the view model:

protected bool _DisableSelection;
private bool _IsSelected;
public bool IsSelected
{
    get { return _IsSelected; }
    set
    {
        if (value == _IsSelected) return;
        _IsSelected = _DisableSelection ? false : value;
        NotifyPropertyChanged();
    }
}

Now you don't have to go hunting!

like image 5
Balki Avatar answered Nov 04 '22 05:11

Balki


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.

like image 1
Daniel Rose Avatar answered Nov 04 '22 05:11

Daniel Rose