TreeView 綁定到深度未知的資料來源

來源:互聯網
上載者:User
有時您可能需要將 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>

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.