WPF HierarchicalDataTemplate
针对具有分层数据结构的控件设计的,比如说TreeView,相当于可以每一个层级上做DataTemplate
XmlDataProvider:数据源,写在Resources下
<XmlDataProvider x:Key="Info" XPath="Nations">
<x:XData>
<Nations xmlns="">
<Nation Name="中国">
<Provinces>
<Province Name="安徽">
<Citys>
<City Name="安庆">
<Countrys>
<Country Name="潜山"/>
<Country Name="桐城"/>
</Countrys>
</City>
<City Name="合肥">
<Countrys>
<Country Name="长丰"/>
<Country Name="肥东"/>
</Countrys>
</City>
</Citys>
</Province>
<Province Name="江苏">
<Citys>
<City Name="南京">
<Countys>
<Country Name="溧水"/>
<Country Name="高淳"/>
</Countys>
</City>
<City Name="苏州">
<Countys>
<Country Name="常熟"/>
</Countys>
</City>
</Citys>
</Province>
</Provinces>
</Nation>
</Nations>
</x:XData>
</XmlDataProvider>
HierarchicalDataTemplate:层级模板,写在Resources下
<HierarchicalDataTemplate DataType="Nation" ItemsSource="{Binding XPath=Provinces/Province}">
<StackPanel Background="AliceBlue">
<TextBlock FontSize="20" Text="{Binding XPath=@Name}"/>
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="Province" ItemsSource="{Binding XPath=Citys/City}">
<StackPanel Background="LightBlue">
<TextBlock FontSize="18" Text="{Binding XPath=@Name}"/>
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="City" ItemsSource="{Binding XPath=Countrys/Country}">
<StackPanel Background="LightBlue">
<TextBlock FontSize="18" Text="{Binding XPath=@Name}"/>
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="Country">
<StackPanel Background="LightSalmon">
<TextBlock FontSize="18" Text="{Binding XPath=@Name}"/>
</StackPanel>
</HierarchicalDataTemplate>
解释
<HierarchicalDataTemplate DataType="Nation" ItemsSource="{Binding XPath=Provinces/Province}">
<StackPanel Background="AliceBlue">
<TextBlock FontSize="20" Text="{Binding XPath=@Name}"/>
</StackPanel>
</HierarchicalDataTemplate>
DataType表示定义的目标是Nation
ItemsSource表示下一级是Provinces/Province (总标签/单个标签名)
StackPanel 定义Nation的外观
XPath=@Name表示绑定为Name属性
比如:
<Nation Name="中国" Age="15">
<HierarchicalDataTemplate DataType="Nation" ItemsSource="{Binding XPath=Provinces/Province}">
<StackPanel Background="AliceBlue">
<TextBlock FontSize="20" Text="{Binding XPath=@Name}"/>
<Label FontSize="15" Content="{Binding XPath=@Age}"></Label>
</StackPanel>
</HierarchicalDataTemplate>
</Nation>
TreeView
<TreeView ItemsSource="{Binding Source={StaticResource ResourceKey=Info},XPath=Nation}"></TreeView>
像引用静态资源一样使用
XPath决定显示的根节点
如果想从第二/三级开始显示,而不是根节点
修改XPath(写路径,否则找不到)
<TreeView ItemsSource="{Binding Source={StaticResource ResourceKey=Info},XPath=Nation/Provinces/Province}"></TreeView>
<TreeView ItemsSource="{Binding Source={StaticResource ResourceKey=Info},XPath=Nation/Provinces/Province/Citys/City}"></TreeView>
学习技术最好的文档就是【官方文档】,没有之一。
还有学习资料【Microsoft Learn】、【CSharp Learn】、【My Note】。
如果,你认为阅读这篇博客让你有些收获,不妨点击一下右下角的【推荐】按钮。
如果,你希望更容易地发现我的新博客,不妨点击一下【关注】。