有時您可能需要將 TreeView 綁定到深度未知的資料來源。如果資料具有遞迴性質,則可能會發生這種情況;檔案系統或公司的組織圖就屬於這種資料,在檔案系統中,檔案夾還可以包含檔案夾,在公司的組織圖中,員工又有自己的直屬員工。
資料來源必須有分層的物件模型。例如,一個 Employee 類可能包含一個由 Employee 對象組成的集合,其中的每個對象都是一位員工的直屬員工。如果資料以未分層方式表示,則您必須構建該資料的分層表示形式。
設定 ItemsControl.
ItemTemplate 屬性時,如果 ItemsControl 為每個子項產生了一個 ItemsControl,則子級 ItemsControl 使用同一 ItemTemplate 作為父級。例如,如果設定綁定到資料的 TreeView 的 ItemTemplate 屬性,則所產生的每個 TreeViewItem 都會使用分配給 TreeView 的 ItemTemplate 屬性的 DataTemplate。
藉助 HierarchicalDataTemplate,您可以在資料範本中為 TreeViewItem 或任何 HeaderedItemsControl 指定 ItemsSource。設定 HierarchicalDataTemplate.
ItemsSource 屬性後,在應用 HierarchicalDataTemplate 時會使用該值。通過使用 HierarchicalDataTemplate,您可以以遞迴方式為 TreeView 中的每個 TreeViewItem 設定 ItemsSource。
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<XmlDataProvider x:Key="myCompany" XPath="Company/Employee">
<x:XData>
<Company xmlns="">
<Employee Name="Don Hall">
<Employee Name="Alice Ciccu">
<Employee Name="David Pelton">
<Employee Name="Vivian Atlas"/>
</Employee>
<Employee Name="Jeff Price"/>
<Employee Name="Andy Jacobs"/>
</Employee>
<Employee Name="Bill Malone">
<Employee Name="Maurice Taylor"/>
<Employee Name="Sunil Uppal"/>
<Employee Name="Qiang Wang"/>
</Employee>
</Employee>
</Company>
</x:XData>
</XmlDataProvider>
<!-- Bind the HierarchicalDataTemplate.ItemsSource property to the employees under
each Employee element. -->
<HierarchicalDataTemplate x:Key="EmployeeTemplate"
ItemsSource="{Binding XPath=Employee}">
<TextBlock Text="{Binding XPath=@Name}" ></TextBlock>
</HierarchicalDataTemplate>
<Style TargetType="TreeViewItem">
<Setter Property="IsExpanded" Value="True"/>
</Style>
</Page.Resources>
<Grid>
<TreeView ItemsSource="{Binding Source={StaticResource myCompany}}"
ItemTemplate="{StaticResource EmployeeTemplate}"/>
</Grid>
</Page>