2013-11-24 54 views
0

我之前沒有使用過TreeView,除了在一些教程中弄懂它們之外。我以爲我有,事實證明我沒有。Treeview沒有顯示我的孩子

我想將我的TreeView綁定到一個對象。

目的是

public List<MyGrandparents> MyGrandParents {get;set;} 

內MyGrandParent類,有一個屬性

public List<MyParents> MyParents{get;set;} 

和最後,MyParent類中有一個屬性

public List<MyChildren> MyChildren {get;set;} 

在每個類,還有其他屬性,如Name(沒有基類,但沒有共享代碼)這個階段)

我想綁定很多樹視圖,所以在'根'級我只看到祖父母。我可以擴大祖父母只看父母,我也可以擴大看到孩子。

我遇到的問題只是最高級別的綁定(祖父級別)。我的XAML是

<TreeView ItemsSource="{Binding MyGrandParents}"> 
     <TreeView.Resources> 
      <DataTemplate DataType="{x:Type local:MyGrandParent}"> 
        <TextBlock Text="{Binding Name}" Margin="0,0,10,0" /> 
      </DataTemplate> 
      <HierarchicalDataTemplate DataType="{x:Type local:MyParent}" ItemsSource="{Binding MyGrandParents}"> 
        <TextBlock Text="Don't bind to test"></TextBlock> 
      </HierarchicalDataTemplate> 
     </TreeView.Resources>    
    </TreeView> 

我失去了爲什麼這不是給我一個不錯的樹。

回答

3

您沒有遵循正確的格式來使用HierarchicalDataTemplate

可能contain children應聲明爲HierarchicalDataTemplateItemsSource設置爲child collection您要顯示它下面的項目。

item not containing any child應該被聲明爲DataTemplate

它應該是這樣的 -

<TreeView.Resources> 
    <HierarchicalDataTemplate DataType="{x:Type local:MyGrandParent}" 
          ItemsSource="{Binding MyParents}"> 
     <TextBlock Text="{Binding Name}" Margin="0,0,10,0" /> 
    </HierarchicalDataTemplate> 
    <HierarchicalDataTemplate DataType="{x:Type local:MyParent}" 
          ItemsSource="{Binding MyChildren}"> 
     <TextBlock Text="Don't bind to test"></TextBlock> 
    </HierarchicalDataTemplate> 
    <DataTemplate DataType="{x:Type local:MyChildren}"> 
     <TextBlock Text="Don't bind to test"></TextBlock> 
    </DataTemplate> 
</TreeView.Resources> 
+0

我是不是在嘗試此倒退?孩子是最低的水平,但在你的例子中,它*看起來是最高的水平? DataTemplate是「根」,所有HierarchicalDataTemplates都是孩子嗎? – Dave

+0

更新的答案與解釋。看一看。 –

+1

多麼好的解釋!再一次感謝你! – Dave