天天看點

WPF TreeView HierarchicalDataTemplate

原文  WPF TreeView HierarchicalDataTemplate

<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.