WPF TreeView分层绑定。

时间:2012-09-21 14:22:48

标签: wpf binding treeview itemssource hierarchicaldatatemplate

刚开始使用wpf。 我需要绑定对象(Hierarchical)文件夹

public class Folder
{
    public Folder()
    {
        this.Name = string.Empty;
        this.Modules = new ObservableCollection<Module>();
        this.Folders = new List<Folder>();
        this.HasChild = false;
    }

    public Folder(Folder parent)
    {
        this.Name = string.Empty;
        this.Modules = new ObservableCollection<Module>();
        this.Folders = new List<Folder>();
        this.HasChild = false;
        this.Parent = parent;
    }

    public bool HasChild { get; set; }

    public string Name { get; set; }

    public List<Folder> Folders { get; set; }

    public ObservableCollection<Module> Modules { get; set; }

    public Folder Parent { get; set; }

    public Folder IfItemExists(string name)
    {
        foreach (Folder folder in Folders)
        {
            if (folder.Name == name)
            {
                return folder;
            }
        }

        return null;
    }
}

到树视图。我这样做

   <TreeView Name="treeView" Margin="5">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Path=Folders}" DataType="{x:Type ModulesUpToDateChecker:Folder}">
                <HierarchicalDataTemplate.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=Name}"></TextBlock>
                    </DataTemplate>
                </HierarchicalDataTemplate.ItemTemplate>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>

并且只有空的docpanel。该对象填写写入。 Eche孩子有自己的孩子,类型相同。

2 个答案:

答案 0 :(得分:4)

HierarchicalDataTemplate已经是一个DataTemplate(它是从它派生的)。所以只需跳过HierarchicalDataTemplate中的ItemTemplate和DataTemplate内容,如下所示:

<TreeView Name="treeView" Margin="5">
  <TreeView.Resources>
    <HierarchicalDataTemplate ItemsSource="{Binding Path=Folders}" DataType="{x:Type WpfApplication220:Folder}">
      <TextBlock Text="{Binding Path=Name}"></TextBlock>
    </HierarchicalDataTemplate>
  </TreeView.Resources>
</TreeView>

哦,您必须以编程方式或在标记中设置树视图的ItemsSource。

treeView.ItemsSource = ..yourFolderList..

答案 1 :(得分:3)

尝试这样做:

 <TreeView Name="treeView" Margin="5">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Path=Folders}" DataType="x:Type ModulesUpToDateChecker:Folder}">
           <Grid>
             <TextBlock Text="{Binding Path=Name}"></TextBlock>
           </Grid>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>