Search code examples
wpfmvvmtreeviewdatatemplateicollectionview

Why doesn't TreeView automatically select DataTemplates for Childnodes after defining TreeView.ItemTemplate?


I don't understand what wpf does here (using .NET 3.5 with C#):

in my Application Resources I defined several DataTemplates and HierarchicalDataTemplates for different Types of ViewModels. So far this works well, and the TreeView in my Window shows the Nodes like expected. I have to say that all Childelements in every ViewModel came as ICollectionView. Now I decided to use the specialities of ICollectionView, to group, sort and filter the "Rootnodes" of the TreeView. I made the TreeView look like this:

<TreeView ItemsSource="{Binding Path=Elements.Groups}">
  <TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Path=Items}" ItemTemplate="{StaticResource SOMEITEMTEMPLATENAME}">
      <TextBlock Text="{Binding Path=Name}"/>
    </HierarchicalDataTemplate>
  </TreeView.ItemTemplate>
</TreeView>

The ViewModel looks like this:

class RootViewModel
  : INotifyPropertyChanged
{

  public ICollectionView Elements
  {
     get
     {
       ICollectionView view = CollectionViewSource.GetDefaultView(_elementsFromModel.Select(x => new FirstChildViewModel(x));
       view.GroupDescriptions.Add(new PropertyGroupDescription("Name"));
       view.Filter = delegate(Object x) { /*do some filter stuff here*/ };

       return view;
     }
  }
}

class FirstchildViewModel
  : INotifyPropertyChanged
{
  /*some other stuff here*/

  public ICollectionView Items
  {
    get;
  }
}

The Problem now is that the TreeView doesn't select autmatically the right Templates for the deeper childelements. So what is wrong with that?


Solution

  • The best solution, after some research would be to define the TreeView like this:

    <TreeView ItemsSource="{Binding Path=Elements}">
      <TreeView.GroupStyle>
        <GroupStyle>
          <GroupStyle.ContainerStyle>
            <Style TargetType="{x:Type GroupItem}">
              <Setter Property="Template">
                <Setter.Value>
                  <ControlTemplate TargetType="{x:Type GroupItem}">
                    <TreeViewItem>
                      <TreeViewItem.Header>
                        <TextBlock Text="{Binding Path=Name}"/>
                      </TreeViewItem.Header>
    
                      <ItemsPresenter Margin="-20,0,0,0"/>
                    </TreeViewItem>
                  </ControlTemplate>
                </Setter.Value>
              </Setter>
            </Style>
          </GroupStyle.ContainerStyle>
        </GroupStyle>
      </TreeView.GroupStyle>
    </TreeView>
    

    now the Group nodes are able to expand and collapse an the different childnodes use different DataTemplates. Thanks to @stukselbax for pointing me to the right direction.