我看到 Windows Phone 工具包有一个名为 HierarchicalDataTemplate
的元素。这对我有好处,因为我想构建一个树结构。
我已经看到 HierarchicalDataTemplate
也包含在 WPF 中。这让我在这里使用这篇文章:TreeView, HierarchicalDataTemplate and recursive Data
它指出您应该在数据模板上设置 TargetType
。但是 Windows Phone 工具包中的 HierarchicalDataTemplate
没有该属性。
此外,我想知道 HierarchicalDataTemplate
是干什么用的,因为似乎也没有 TreeView
控件。
最佳答案
有趣的问题,我刚刚查了一下,确实,原生WP8中没有HierarchicalDataTemplate,但它在WPToolkit中。在查看源代码后,它仅在 HeaderedItemsControl 中使用,它是 ExpanderView 和 MenuItem 的父级。
有趣的是,HierarchicalDataTemplate 中的属性 ItemsSource、ItemTemplate 和 ItemContainerStyle 甚至都不是 DependencyProperties,它们甚至没有在任何 WPToolkit 示例中分配。我不确定这个 HierarchicalDataTemplate 实际上是否可用于创建递归数据结构。
但没关系,完全可以只使用 native WP8 类来构建您自己的递归数据结构:
让我们有一个简单的递归类 Node 和带有节点集合的 MainViewModel:
public class Node
{
public string Title { get; set; }
public ObservableCollection<Node> Children { get; set; }
}
public class MainViewModel
{
public ObservableCollection<Node> Nodes { get; set; }
public MainViewModel()
{
Nodes = ... // load the structure here
}
}
让我们创建用于递归显示节点的 UserControl 和 MainPage 的一些代码。
<UserControl x:Class="WP8.HierarchicalDataTemplate.NodeUserControl"
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:h="clr-namespace:WP8.HierarchicalDataTemplate">
<Border BorderThickness="1" BorderBrush="Red">
<StackPanel d:DataContext="{d:DesignInstance h:Node}" Margin="15">
<TextBlock Text="{Binding Title}" />
<ItemsControl ItemsSource="{Binding Children}"
ItemTemplate="{StaticResource NodeNestedTemplate}" />
</StackPanel>
</Border>
</UserControl>
<!-- on MainPage as root object -->
<Grid>
<ItemsControl Margin="20"
ItemsSource="{Binding Nodes, Source={StaticResource model}}"
ItemTemplate="{StaticResource NodeNestedTemplate}" />
</Grid>
请注意,我们在 NodeUserControl 和 MainPage DataTemplate 中都使用了名为 NodeNestedTemplate 的数据模板。我们不能像那样定义递归 DataTemplate,但我们可以创建使用此 DataTemplate 并放置在此 DataTemplate 中的 UserControl - 这是 App.xaml 中的全局资源:
...
xmlns:h="clr-namespace:WP8.HierarchicalDataTemplate">
<Application.Resources>
<h:MainViewModel x:Key="model"/>
<DataTemplate x:Key="NodeNestedTemplate">
<h:NodeUserControl />
</DataTemplate>
</Application.Resources>
...
仅此而已!这是使用具有 3 级递归的数据源时的解决方案的小屏幕截图:http://i.stack.imgur.com/zqOYe.png
希望对你实现树结构有所帮助!
关于c# - Windows Phone 使用 HierarchicalDataTemplate 进行递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19861290/