共用方式為


HOW TO:將樹狀檢視繫結至未知深度的資料

有時您會想要將 TreeView 繫結至資料深度未知的資料來源。 當資料具有遞迴的性質時,就可能發生這種情況。這類資料的範例包括檔案系統 (資料夾能包含資料夾)、公司組織結構 (任何員工都有可能是其他員工的直屬上級) 等等。

資料來源必須有階層式物件模型 (Object Model)。 舉例來說,Employee 類別可能包含本身為直屬報告者員工之 Employee 物件的集合。 如果資料的表示方式不是階層式,您就必須建置資料的階層式表示。

當您設定 ItemsControl.ItemTemplate 屬性時,如果 ItemsControl 為每個子項目產生 ItemsControl,則子系 ItemsControl 會使用和父代一樣的 ItemTemplate。 舉例來說,如果您在資料繫結 TreeView 上設定 ItemTemplate 屬性,則每一個產生的 TreeViewItem 都會使用已指派給 TreeViewItemTemplate 屬性的 DataTemplate

HierarchicalDataTemplate 可以讓您在資料樣板 (Template) 上指定 TreeViewItemItemsSource,或是任何 HeaderedItemsControl。 如果您設定 HierarchicalDataTemplate.ItemsSource 屬性,則在套用 HierarchicalDataTemplate 的時候才會使用這個屬性值。 藉由使用 HierarchicalDataTemplate,您就可以在 TreeView 中為每個 TreeViewItem 遞迴設定 ItemsSource

範例

在下列範例中,會示範如何將 TreeView 繫結至階層式資料,並使用 HierarchicalDataTemplate 來為每個 TreeViewItem 指定 ItemsSourceTreeView 會繫結至表示公司員工的 XML 資料。 每個 Employee 項目都能包含其他 Employee 項目來表示直屬報告者。 因為是遞迴性資料,所以每一層都能套用 HierarchicalDataTemplate

<Page 
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml">
  <Page.Resources>
    <XmlDataProvider x:Key="myCompany" XPath="Company/Employee">
      <x:XData>
        <Company >
          <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>

請參閱

概念

資料繫結概觀

資料範本化概觀