2012-09-21 157 views
5

剛開始使用wpf。 我需要的對象(分層)文件夾WPF TreeView分層綁定。

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兒童擁有相同類型的自己的孩子。

回答

4

HierarchicalDataTemplate已經是一個DataTemplate(它派生自它)。因此,只要跳過的ItemTemplate和DataTemplate的東西你HierarchicalDataTemplate裏面像這樣:

<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.. 
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>