2012-03-31 101 views
1

我有一個奇怪的WPF/XAML問題。默認情況下,我想要擴展此TreeView中的所有節點。最終我會將其綁定到我的視圖模型,但現在我只是希望它們都默認展開。TreeView的子節點展開,但根節點沒有

這是有問題的代碼的一部分(即我目前使用)

<HierarchicalDataTemplate DataType="{x:Type Model:DirectoryItem}" 
          ItemsSource="{Binding Items}"> 
    <TextBlock Text="{Binding Path=Name}" 
       ToolTip="{Binding Path=Path}" /> 
    <HierarchicalDataTemplate.ItemContainerStyle> 
     <Style TargetType="TreeViewItem"> 
      <Setter Property="IsExpanded" Value="True" /> 
     </Style> 
    </HierarchicalDataTemplate.ItemContainerStyle> 
</HierarchicalDataTemplate> 

<DataTemplate DataType="{x:Type Model:FileItem}"> 
    <TextBlock Text="{Binding Path=Name}" 
       ToolTip="{Binding Path=Path}" /> 
</DataTemplate> 

特別是,如果我有setter屬性爲IsExpanded的一部分。

正如您在下面的圖片中可以看到的,此代碼具有排序功能。如果我展開根節點,則默認情況下所有內容都會展開。

但爲什麼默認情況下根節點還沒有擴展?我不知道爲什麼這樣做。

enter image description here enter image description here

回答

1

,因爲你要添加的風格,以分層數據模板他們沒有可能擴大,適用於兒童的唯一(唯一的理論,雖然)。在DataTemplate中使用樣式是一種代碼異味 - 它是數據模板,而不是可視化表示,所以它不應該包含treeViewItem的樣式(下次可能是其他層次的樣式)。

我想你做這樣的:

<TreeView.ItemContainerStyle> 
      <Style TargetType="TreeViewItem"> 
       <Setter Property="TreeViewItem.IsExpanded" Value="True"/> 
      </Style> 
</TreeView.ItemContainerStyle> 
+0

謝謝,這工作。謝謝你的解釋。我確實有一個後續問題(我對WPF相當陌生) - 如果我沒有將它放在分層數據模板中,將來我仍然可以將它綁定到DirectoryItem對象的IsExpanded屬性中?謝謝 – theqs1000 2012-03-31 12:44:02

+0

您可以在當前的解決方案中使用{Binding YourPropertyName}而不是「True」。 – 2012-03-31 12:53:59