如何为自定义控件提供递归数据模板

时间:2014-10-30 04:45:47

标签: wpf xaml dynamicresource

我有一个自定义控件,它基本上是一种TreeView。现在问题是我需要在TreeView控件中有任何级别的细节,所以我想出了以下数据模板

我有以下Generic.xaml

<DataTemplate x:Key="treetemplate">
    <StackPanel>
     <TextBlock Text="{Binding Label}" ></TextBlock>
     <ItemsControl ItemsSource="{Binding Children}" ItemTemplate="{DynamicResource treetemplate}" />
    </StackPanel>
</DataTemplate>

<ControlTemplate TargetType="{x:Type local:CustomControl1}" x:Key="testkey">
    <ControlTemplate.Resources>
        <local:AnythingToListConverter x:Key="anyconv"></local:AnythingToListConverter>
    </ControlTemplate.Resources>
    <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
        <ItemsControl ItemsSource="{Binding Root, Converter={StaticResource anyconv}}" ItemTemplate="{StaticResource treetemplate}"  />
    </Border>
</ControlTemplate>

<Style TargetType="{x:Type local:CustomControl1}">
    <Setter Property="Template" Value="{StaticResource testkey}" />
</Style>

这是我的自定义控件构造函数

        this.Root = new Node();

        this.Root.Label = "Root";
        this.Root.Children = new List<Node>();

        this.Root.Children.Add(new Node(){Label="Child1"});
        this.DataContext = this;

这就是控制的样子

Control

以下是我认为问题  对于相同模板的递归调用,我使用的是DynamicResource。从来没有在我的工作和实际资源从未被调用。如果我将其更改为StaticResource,则无法编译,因为它无法看到自己。我该如何解决?

完整的解决方案可以是downloaded here

1 个答案:

答案 0 :(得分:2)

您需要的是 HierarchicalDataTemplate 。它的设计精确地指出了这种情况。 以下是您使用它的方式:

<HierarchicalDataTemplate ItemsSource="{Binding Children}" 
                          DataType="{x:Type local:Node}">
    <TextBlock Text="{Binding Label}" ></TextBlock>
</HierarchicalDataTemplate>

请注意,使用此模板时,我们必须将其DataType设置为您的数据项的类型(在这种情况下,我猜它是Node)。另外我猜你不需要任何自定义控件,只需使用默认的TreeView,并将此模板定义为这样的资源:

<TreeView ItemsSource="{Binding Root, Converter={StaticResource anyconv}}">
</TreeView>

如果您仍想保留代码,请尝试将ItemsControl替换为TreeView或某些HeaderedItemsControlHierarchicalDataTemplate仅用于HeaderedItemsControlTreeView也只是一种HeaderedItemsControl)。