5

刚从 wpf 开始。我需要绑定对象(分层)文件夹

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>

并且只有空的文档面板。对象被填充写入。Eche child 有自己的具有相同类型的孩子。

4

2 回答 2

5

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..
于 2012-09-21T14:43:16.803 回答
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>
于 2012-09-21T14:45:44.697 回答