<StackPanel Margin="0,0,0,0">
<StackPanel.Resources>
<HierarchicalDataTemplate x:Key="MonTemp" DataType = "{x:Type local:MonthViewModel}" ItemsSource = "{Binding FileInfoViewModels}">
<TextBlock Text="{Binding MonthDescription}"/>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate DataType="{x:Type local:FileInfoViewModel}">
<TextBlock Text="{Binding FileName}"/>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate x:Key="YearTemp" DataType = "{x:Type local:YearViewModel}" ItemsSource = "{Binding MonthViewModels}" ItemTemplate="{StaticResource MonTemp}">
<TextBlock Text="{Binding YearDescription}"/>
</HierarchicalDataTemplate>
</StackPanel.Resources>
<TreeView Height="100" Name="fileTree">
<TreeView.Resources>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="True"/>
</Style>
</TreeView.Resources>
<TreeViewItem ItemsSource="{Binding TreeViewModels}" Header="Back up View" ItemTemplate="{StaticResource YearTemp}"/>
</TreeView>
</StackPanel>
HierarchicalDataTemplate 的DataType是本层的绑定,而ItemsSource是绑定下层的对象集合,它只能使用两层集合,如MonTemp,如果要用到三层以上,需要两个HierarchicalDataTemplate,用ItemTemplate引用另外一个。
HierarchicalDataTemplate绑定后,子节点都是直接绑定DataSource的Object,并非TreeViewItem,所以要全部默认展开的话,要用TreeView.Resources设置Style.