您需要做的是创建一个查询,以某种方式按类别对您的项目进行分组(您已经拥有它,或者您可以使用 linq 通过 Group By ... Into 查询创建您的层次结构)。
然后,您可以使用绑定到查询结果的 ItemsControl,使用包含标题的 ItemTemplate 和另一个 ItemsControl 显示数据,后者的 ItemsPanelTemplate 设置为 WrapPanel 或 UniformGrid。
假设您设法在以下类中获取数据(抱歉,这里是 VB,但如果您需要,C# 不会太远):
Public Class Category
Private _Name As String
Public Property CategoryName() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
Private _SubCategories As New List(Of SubCategory)
Public Property SubCategories() As List(Of SubCategory)
Get
Return _SubCategories
End Get
Set(ByVal value As List(Of SubCategory))
_SubCategories = value
End Set
End Property
End Class
Public Class SubCategory
Private _Name As String
Public Property SubCategoryName() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
End Class
<ItemsControl ItemsSource="{Binding QueryResult}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1"
BorderBrush="Black">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border BorderThickness="1"
BorderBrush="Black">
<TextBlock Margin="2"
Text="{Binding CategoryName}" />
</Border>
<ItemsControl Grid.Row="1"
ItemsSource="{Binding SubCategories}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1"
BorderBrush="Black">
<TextBlock Margin="2"
Text="{Binding SubCategoryName}" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="3" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
这是一个非常粗糙的模板,您必须修改边框才能获得所需的内容,但这可以解决问题。