1、xaml 文件
<Window x:Class="DataTemplate.HierarchicalDataTemplateWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window6" Height="268" Width="362">
<Window.Resources>
<!--数据源-->
<XmlDataProvider x:Key="ds" Source="data.xml" XPath="Data/Grade"></XmlDataProvider>
<!--年级模板-->
<HierarchicalDataTemplate DataType="Grade" ItemsSource="{Binding XPath=Class}">
<TextBlock Text="{Binding XPath=@Name}"></TextBlock>
</HierarchicalDataTemplate>
<!--班级模板-->
<HierarchicalDataTemplate DataType="Class" ItemsSource="{Binding XPath=Group}">
<RadioButton Content="{Binding XPath=@Name}" GroupName="gn"></RadioButton>
</HierarchicalDataTemplate>
<!--小组模板-->
<HierarchicalDataTemplate DataType="Group" ItemsSource="{Binding XPath=Student}">
<CheckBox Content="{Binding XPath=@Name}"></CheckBox>
</HierarchicalDataTemplate>
</Window.Resources>
<Grid>
<TreeView Margin="5" ItemsSource="{Binding Source={StaticResource ds}}">
</TreeView>
</Grid>
</Window>
2、xaml后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace DataTemplate
{
/// <summary>
/// HierarchicalDataTemplateWindow.xaml 的交互逻辑
/// </summary>
public partial class HierarchicalDataTemplateWindow : Window
{
public HierarchicalDataTemplateWindow()
{
InitializeComponent();
}
}
}
3、xml文件:
<?xml version="1.0" encoding="utf-8" ?>
<Data xmlns="">
<Grade Name="一年级">
<Class Name="甲班">
<Group Name="A组">
</Group>
<Group Name="B组">
</Group>
<Group Name="C组">
</Group>
</Class>
<Class Name="乙班">
<Group Name="A组">
</Group>
<Group Name="B组">
</Group>
<Group Name="C组">
</Group>
</Class>
</Grade>
<Grade Name="二年级">
<Class Name="甲班">
<Group Name="A组">
</Group>
<Group Name="B组">
</Group>
<Group Name="C组">
</Group>
</Class>
<Class Name="乙班">
<Group Name="A组">
</Group>
<Group Name="B组">
</Group>
<Group Name="C组">
</Group>
</Class>
</Grade>
</Data>