TreeView仅加载顶级节点

时间:2010-12-02 22:59:45

标签: c# silverlight silverlight-4.0

我有一个节点类,我试图用它来填充Silverlight中的TreeView:

class TreeNode {
    public string Caption {get; set;};
    public IEnumerable<TreeNode> Children{get; set;}

}

我的XAML如下:

<controls:TreeView VerticalAlignment="Stretch" 
                          x:Name="trv"
                          Height="150" >
            <controls:TreeView.ItemTemplate>
                <common:HierarchicalDataTemplate ItemsSource="{Binding Path=Children}" >
                    <TextBlock Text="{Binding Path=Caption}" />
                </common:HierarchicalDataTemplate>
            </controls:TreeView.ItemTemplate>
        </controls:TreeView>

但是,只加载第一层元素。如果我用HerarchicalDataTemplate替换TextBlock,基本上硬编码我的数据深度,则显示第二层元素。然而,第三层则没有。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我刚试过这个,你必须在数据绑定部分做错事,因为一切都按预期工作。我在下面用你的XAML创建了一个简单的例子。

<强>输出:

alt text

<强> XAML:

<controls:TreeView VerticalAlignment="Stretch"  
                  x:Name="trv"
                  Height="150" >
    <controls:TreeView.ItemTemplate>
        <controls:HierarchicalDataTemplate ItemsSource="{Binding Path=Children}" >
            <TextBlock Text="{Binding Path=Caption}" />
        </controls:HierarchicalDataTemplate>
    </controls:TreeView.ItemTemplate>
</controls:TreeView>

<强>代码:

    TreeNode myNode = new TreeNode() { Caption = "Parent" };
    List<TreeNode> myChildren = new List<TreeNode>();

    myChildren.Add(new TreeNode() { Caption = "First Child" });
    myChildren.Add(new TreeNode() { Caption = "Second Child", Children = new List<TreeNode>() { new TreeNode() { Caption = "Child on 3rd Level" } } });


    myNode.Children = myChildren;
    trv.ItemsSource = new List<TreeNode>() { myNode };