2009-08-03 92 views
0

我有一個包含遵循此結構的對象的列表。這不是我正在使用的真正的課程,而是應該解釋這個概念。WPF HierarchicalDataTemplate&ItemsControl

CLASSES

public class BaseType{} 
public class TypeA : BaseType{} 
public class TypeB: BaseType 
{ 
    public List<TypeA> TypeAList { get; private set; } 
} 

的ItemsControl的結合列表中是一個List<BaseType>

XAML現在

<ItemsControl> 
    <ItemsControl.Resources> 
     <HierarchicalDataTemplate DataType="{x:Type local:TypeB}" ItemsSource = "{Binding Path=TypeAList}"> 
      <DataTemplate.Resources> 
       <Style TargetType="TextBlock"> 
        <Setter Property="FontSize" Value="18"/> 
        <Setter Property="HorizontalAlignment" Value="Center"/> 
       </Style> 
      </DataTemplate.Resources> 
      <Grid> 
       <Ellipse Fill="Gold"/> 
       <StackPanel> 
        <TextBlock Margin="3,3,3,0" 
     Text="{Binding Path=Description}"/> 
        <TextBlock Margin="3,0,3,7" 
     Text="{Binding Path=Name}"/> 
       </StackPanel> 
      </Grid> 
     </HierarchicalDataTemplate> 
    <ItemsControl.Resources> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <StackPanel></StackPanel> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
</ItemsControl> 

我期望看到的是所有類型A的對象在TypeB對象屬性中找到要顯示在Ite中msControl,而是我只看到TypeB對象,顯示爲爲HierarchicalDataTemplate定義的樣式。我在TreeView控件中使用了相同的數據模式,它顯示的子項很好。

  • 你不能在ItemsControl中使用HierarchicalDataTemplate嗎?
  • 你如何去在ItemsControl中顯示父子關係?

回答

1

您確實需要研究模板並使用TreeView控件,或者構建自己的控件以處理分層數據。

在某些情況下,你可以設計自己的數據模板進行常規項目控制,其嵌套控件綁定到項目,如(僞)

<HierarchicalDataTemplate> 
    <Grid DataContext="{Binding}"> 
     <ListBox ItemsSource="{Binding TypeAList}" /> 
    </Grid> 
</HierarchicalDataTemplate> 

沒有嘗試過的代碼上述

控制需要知道的HierarchicalDataTemplate的 - 並且在上面的例子中,控制被簡單地使用它作爲一個DataTemplate(HierarchicalDataTemplate從DataTemplate中導出用於在樣式簡單和的DependencyProperty的類型,該數據模板)。