3

我似乎无法弄清楚如何让 TreeView 显示我检查过的列表,但无法找到相同的场景,叶子似乎总是对象而不是简单的字符串。我无法弄清楚 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>
4

0 回答 0