<Window x:Class="HierarchicalDataTemplate.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:HierarchicalDataTemplate"
mc:Ignorable="d"
Title="HierarchicalDataTemplate" Height="300" Width="300">
<Window.Resources>
<!--数据源-->
<XmlDataProvider x:Key="ds" Source="Data.xml" XPath="Data/Grade"/>
<!--年级模板-->
<HierarchicalDataTemplate DataType="Grade" ItemsSource="{Binding XPath=Class}">
<TextBlock Text="{Binding XPath=@Name}"/>
</HierarchicalDataTemplate>
<!--班级模板-->
<HierarchicalDataTemplate DataType="Class" ItemsSource="{Binding XPath=Group}">
<RadioButton Content="{Binding XPath=@Name}" GroupName="gn"/>
</HierarchicalDataTemplate>
<!--小组模板-->
<HierarchicalDataTemplate DataType="Group" ItemsSource="{Binding XPath=Student}">
<CheckBox Content="{Binding XPath=@Name}"/>
</HierarchicalDataTemplate>
</Window.Resources>
<Grid>
<TreeView Margin="5" ItemsSource="{Binding Source={StaticResource ds}}"/>
</Grid>
</Window>
这是xaml文件,下面是外部的Data.xml文件,书上说或放在项目根目录,我试了不行,必须用绝对路径,书上就是相对路径,直接source=文件名。
<?xml version="1.0" encoding="utf-8"?>
<Data xmlns="">
<Grade Name="一年级">
<Class Name="甲班">
<Group Name="A组"/>
<Group Name="B组"/>
<Group Name="C组"/>
</Class>
<Class Name="乙班">
<Group Name="A组"/>
<Group Name="B组"/>
<Group Name="C组"/>
</Class>
</Grade>
<Grade Name="二年级">
<Class Name="甲班">
<Group Name="A组"/>
<Group Name="B组"/>
<Group Name="C组"/>
</Class>
<Class Name="乙班">
<Group Name="A组"/>
<Group Name="B组"/>
<Group Name="C组"/>
</Class>
</Grade>
</Data>
这是 Windows 开发吧 , 发错板块了