TreeView绑定列表<string> </string>

时间:2012-10-04 17:20:49

标签: treeview hierarchicaldatatemplate

我似乎无法弄清楚如何让TreeView显示List 我检查了SO,但是无法找到相同的场景,叶子似乎总是对象而不是简单的字符串。 我无法弄清楚HierarchicalDataTemplate和DataTemplate的正确组合以使其工作。使用以下对象。绑定发生我只看到第一级而不是叶子。

    public class Trunk
    {
    public Trunk(string tn)
    {
        TrunkName = tn;
        Branches = new List<Branch>();
    }
    public List<Branch> Branches { get; set; }

    public string TrunkName { get; set; }
}
public class Branch
{
    public Branch(string bn)
    {
        BranchName = bn;
        Leaves = new List<string>();
    }
    public List<string> Leaves { get; set; }

    public string BranchName { get; set; }

}



Tree = new Trunk("Root")
    {
        Branches =
            {
                new Branch("Branch1"){Leaves = {"Leaf1","Leaf2"}},
                new Branch("Branch2"){Leaves = {"Leaf3","Leaf4"}}
            }

    };

以下模板

 <TreeView ItemsSource="{Binding Trees}" >
    <TreeView.ItemTemplate>
    <HierarchicalDataTemplate  ItemsSource="{Binding Branches}">
        <TextBlock Text="{Binding Path=TrunkName}" />
            <HierarchicalDataTemplate.ItemTemplate >
                <DataTemplate>
                    <TextBlock Text="{Binding BranchName}"/>
                </DataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

编辑: 当然,在花了几天试图弄清楚什么不是点击之后。我在张贴求助后想出来了 PS TreeView ItemsSource是从绑定到Window DataContext的ViewModel设置的。

<TreeView ItemsSource="{Binding Trees}" >
    <TreeView.ItemTemplate>
    <HierarchicalDataTemplate  ItemsSource="{Binding Branches}">
        <TextBlock Text="{Binding Path=TrunkName}" />
            <HierarchicalDataTemplate.ItemTemplate >
                <HierarchicalDataTemplate ItemsSource="{Binding Leaves}">
                    <TextBlock Text="{Binding BranchName}"/>
                    <HierarchicalDataTemplate.ItemTemplate >
                        <DataTemplate>
                            <TextBlock Text="{Binding }"/>
                        </DataTemplate>
                    </HierarchicalDataTemplate.ItemTemplate>
                </HierarchicalDataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

0 个答案:

没有答案