如何:将 TreeView 绑定到具有不确定深度的数据

有时,需要将深度 TreeView 未知的数据源绑定到数据源。 当数据本质上是递归的(例如文件系统),其中文件夹可以包含文件夹或公司的组织结构(员工将其他员工作为直接报告)时,可能会发生这种情况。

数据源必须具有分层对象模型。 例如,类 Employee 可能包含 Employee 对象的集合,这些对象是员工的直接下属。 如果数据以非分层方式表示,则必须生成数据的分层表示形式。

设置 ItemsControl.ItemTemplate 属性时,如果 ItemsControl 为每个子项生成一个 ItemsControl ,则子 ItemsControl 项使用与父项相同的 ItemTemplate 值。 例如,如果在数据绑定上设置ItemTemplate属性,则生成的每个TreeViewItem属性都使用DataTemplate分配给ItemTemplate该属性的属性TreeViewTreeView

这样HierarchicalDataTemplate,便可以在数据模板上指定ItemsSource一个或多个TreeViewItemHeaderedItemsControl值。 设置 HierarchicalDataTemplate.ItemsSource 属性时,应用该值时 HierarchicalDataTemplate 使用该值。 通过使用 aHierarchicalDataTemplate,可以递归设置ItemsSourceTreeViewItem每个项。TreeView

示例:

下面的示例演示如何绑定到 TreeView 分层数据,并使用 a HierarchicalDataTemplate 指定 ItemsSource 每个 TreeViewItem数据。 TreeView 组件绑定到表示公司员工的 XML 数据。 每个 Employee 元素可以包含其他 Employee 元素,以指示向谁报告谁。 由于数据是递归的 HierarchicalDataTemplate ,因此可以应用于每个级别。

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

另请参阅