问题
I have a list containing objects that follow this structure. This is not the real classes I am working with, but should explain the concept.
CLASSES
public class BaseType{}
public class TypeA : BaseType{}
public class TypeB: BaseType
{
public List<TypeA> TypeAList { get; private set; }
}
The List that the ItemsControl binds to is a 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>
Now what I would expect to see is all the TypeA objects found in the TypeB object property to be displayed in the ItemsControl, instead I only see the TypeB objects, displayed with the styles defined for the HierarchicalDataTemplate. i've used the same datatemplate in a TreeView control, where it displays the child items fine.
- Can you not use a HierarchicalDataTemplate in an ItemsControl?
- How do you go about displaying a parent child relationship in an ItemsControl?
回答1:
You really need to look into templating and working with the TreeView control, or build your own control to work with the hierarchical data.
In some situations, you may be able to design your own data template for a regular items control whose nested controls bind to the item, such as (psuedo)
<HierarchicalDataTemplate>
<Grid DataContext="{Binding}">
<ListBox ItemsSource="{Binding TypeAList}" />
</Grid>
</HierarchicalDataTemplate>
Haven't tried the code above
The control needs to be aware of the HierarchicalDataTemplate - and in the example above, the control is simply using it as a DataTemplate (HierarchicalDataTemplate derives from DataTemplate for simplicity in styles and the DependencyProperty's type for that data template).
来源:https://stackoverflow.com/questions/1222008/wpf-hierarchicaldatatemplate-itemscontrol