Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF TreeView Items not selectable

I am currently writing an Folder Browser Dialog in WPF. For displaying the Tree I use an TreeView:

<TreeView Name="FolderView" ItemsSource="{Binding DataTrees}" Grid.Row="0">
    <TreeView.ItemTemplate>
      <HierarchicalDataTemplate ItemsSource="{Binding Tree}">
      <TreeViewItem IsSelected="{Binding IsSelected, Mode=TwoWay}" IsExpanded="{Binding IsExpanded, Mode=TwoWay}" Header="{Binding Name}" HorizontalAlignment="Left"/>
      </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
  </TreeView>

Currently I have three Problems:

  1. You can't select an Item in the running Programm
  2. The Header is about two tabs to the right (not critical but ugly)
  3. 'IsExpanded' is only set when double clicking an item and not on clicking [+]

I don't know where the Problem is so please comment and I will update my Question!

EDIT: The Itemsource is a List Data Tree Class:

public class DataTree:INotifyPropertyChanged
{
  private string path;

  private string name;

  private ObservableCollection<DataTree> tree;

  private bool isSelected;

  private bool isExpanded;
}

(simple Code - Without Propertys and Implementation Of INotifyPropertyChanged)

like image 775
Bio42 Avatar asked Sep 23 '14 08:09

Bio42


1 Answers

Do not add TreeViewItem into ItemTemplate directly:

<TreeView Name="FolderView" ItemsSource="{Binding DataTrees}" Grid.Row="0">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">    
            <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
            <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
            <Setter Property="HorizontalAlignment" Value="Left"/>
        </Style>    
    </TreeView.ItemContainerStyle>

    <TreeView.ItemTemplate>
      <HierarchicalDataTemplate ItemsSource="{Binding Tree}">
          <TextBlock Text="{Binding Name}"/>
      </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

As any ItemsControl, TreeView wraps its data items into item container (TreeViewItem in your case). Hence, things like selection and expansion should be set via ItemContainerStyle.

like image 144
Dennis Avatar answered Sep 21 '22 02:09

Dennis