2009-12-07 81 views
0

由於我寫的屬性用於使用ItemsControl構建3層樹視圖,因此我的同事威脅要今天將我放在TheDailyWTF上。在多級樹視圖上使用ItemsControl

我捨不得你的足跡:

ObservableCollection<KeyValuePair<string, ObservableCollection<KeyValuePair<string, ObservableCollection<MyType>>>>>; 

我的目標是創建一個能夠使用密鑰作爲頭一個ItemsControl,和值作爲的ItemsSource爲3個層次:

<Style x:Key="filterTreeStyle" TargetType="ItemsControl"> 
     <Setter Property="ItemTemplate"> 
      <Setter.Value> 
       <DataTemplate> 
        <controls:TreeViewItem IsExpanded="True"> 
         <controls:TreeViewItem.Header> 
          <controlsToolkit:TreeViewItemCheckBox Content="{Binding Key}"/> 
         </controls:TreeViewItem.Header> 
         <ItemsControl ItemsSource="{Binding Value}"> 
          <ItemsControl.ItemTemplate> 
           <DataTemplate> 
            <controls:TreeViewItem> 
            <controls:TreeViewItem.Header> 
             <controlsToolkit:TreeViewItemCheckBox Content="{Binding Key}"/> 
            </controls:TreeViewItem.Header> 
             <controlsToolkit:TreeViewItemCheckBox IsChecked="{Binding Enabled}" Content="{Binding FilterTypeText}"/> 
            </controls:TreeViewItem> 
           </DataTemplate> 
          </ItemsControl.ItemTemplate> 
         </ItemsControl> 
        </controls:TreeViewItem> 
       </DataTemplate> 
      </Setter.Value> 
     </Setter> 
     </Style> 

燦任何人將我從TheDailyWTF的魔掌中拯救出來?什麼是更乾淨的方式來做到這一點。如果我們能夠找出一種方法使動態數量級別化,那麼就可以獲得獎勵。

回答

3

呃,也許我在這裏是愚蠢的,但既然你想要一個TreeView ...爲什麼不使用TreeView?您還需要使用HierarchicalDataTemplate而不是vanilla DataTemplate:HDT的內容成爲Header,而ItemsSource則用於創建子節點。這也會照顧到動態的層數。

TreeView內置於WPF中,並作爲SDK的一部分在Silverlight中提供。

+0

不知道HDT ...看起來我可以使用它。在ItemsSource方面並沒有真正改變任何東西(這意味着我沒有深度的遞歸方法)。 – 2009-12-07 23:53:21

+0

不確定您的意思是ItemsSource屬性端還是數據模型端?如果前者使用KeyValuePair的Value,就像您現在使用的那樣。因此,。如果後者是真的,但無論如何你最好創建一個分層數據結構,而不是使用深度嵌套的KVP佈局 - 這會給你比Key和Value更有意義的名字!例如。 'class TreeNode {string Title; ObservableCollection 孩子; }' – itowlson 2009-12-08 00:35:37

+0

我使用了HDT,它的效果很好。因爲Silverlight的風格要求每個'等級'具有相同的屬性名稱,所以我不需要具有「聯盟」,「分部」和「團隊」屬性,而是需要每個對象都具有「選項」 。 – 2009-12-09 18:09:32