2014-02-09 57 views
2

好吧,我現在不明白。我搜索谷歌和#1一會兒,看到的例子如何使用HierarchicalDataTemplateTreeView的HierarchicalDataTemplate

我有一個叫Class類,它看起來像很多的:

[Table(Name = "Class")] 
public class Class 
{ 
    [Column(IsDbGenerated = true, IsPrimaryKey = true)] 
    public int Id { get; private set; } 

    [Column] 
    public string ClassName { get; set; } 
} 

而且我有一個叫Pupil類看起來像:

[Table(Name = "Pupil")] 
public class Pupil 
{ 
    [Column(IsPrimaryKey = true, IsDbGenerated = true)] 
    public int Id { get; private set; } 

    public Name Name 
    { 
     get { return this.nameEntityRef.Entity; } 
     set 
     { 
      this.nameEntityRef.Entity = value; 
      this.NameId = value.Id; 
     } 
    } 

    public Address Address 
    { 
     get { return this.addressEntityRef.Entity; } 
     set 
     { 
      this.addressEntityRef.Entity = value; 
      this.AddressId = value.Id; 
     } 
    } 

    public Class Class 
    { 
     get { return this.classEntityRef.Entity; } 
     set 
     { 
      this.classEntityRef.Entity = value; 
      this.ClassId = value.Id; 
     } 
    } 

    private EntityRef<Name> nameEntityRef; 
    private EntityRef<Address> addressEntityRef; 
    private EntityRef<Class> classEntityRef; 

    [Column] 
    internal int AddressId { get; set; } 

    [Column] 
    internal int NameId { get; set; } 

    [Column] 
    internal int ClassId { get; set; } 
} 

我引入了一個名爲ClassPupils類,它看起來像

public class ClassPupils 
{ 
    public ClassPupils(Class @class) 
    { 
     this.Class = @class; 
     this.Pupils = new List<Pupil>(); 
    } 

    public Class Class { get; set; } 
    public List<Pupil> Pupils { get; set; } 
} 

ClassPupils應持有所有學生在一個班。

現在我想創建一個TreeView,其中所有Pupil s在那裏列出Class。因此,我在我的ViewModel中使用了一個ObservableCollection<ClassPupils>。在我看來,我綁定到這個集合。我查看-代碼TreeView的樣子:

<TreeView Grid.Row="0" Grid.Column="0" Margin="2" ItemsSource="{Binding ClassPupils}"> 
    <TreeView.Resources> 
     <HierarchicalDataTemplate DataType="{x:Type model:ClassPupils}" ItemsSource="{Binding Class}"> 
      <Label Content="{Binding Class.ClassName}"/> 
     </HierarchicalDataTemplate> 
     <DataTemplate DataType="{x:Type entity:Pupil}"> 
      <Label Content="{Binding Name.Lastname}"/> 
     </DataTemplate> 
    </TreeView.Resources> 
</TreeView> 

但我只得到了類,而不是針對學生,姓的TreeViewItems。我究竟做錯了什麼?

回答

4

ItemsSource爲HierarchicalDataTemplate應該Pupils

它應該指向包含孩子的這個DataTemplate中這是Pupils,而不是Class集合。

<HierarchicalDataTemplate DataType="{x:Type model:ClassPupils}" 
          ItemsSource="{Binding Pupils}"> 
    <Label Content="{Binding Class.ClassName}"/> 
</HierarchicalDataTemplate> 
+0

它可以完美運行。你介意在短時間內解釋一下,所以我能理解它嗎? – Tomtom

+0

在答案中添加了解釋。 –

+0

完美。我會在10分鐘內接受你的答案:) – Tomtom

相關問題