是的,这是可能的。我将向您展示改编自我在另一个 ItemsControl 中使用 ItemsControl 的项目的示例。这可以适应 ItemsControl 以外的其他容器,但 ItemsControl 提供了最大的灵活性。
如果我理解正确,您希望显示经销商列表,并且对于每个经销商,您希望显示汽车列表。
对于每个 ResellerInfo 项目,外部 ItemsControl 将显示一个带有 TextBlock 的 StackPanel 和另一个显示 Cars 的 ItemsControl。
然后,内部 ItemsControl 会显示一个 StackPanel,其中包含每辆汽车的型号和年份。请注意,内部的 DataContext 会自动设置为 CarInfo 的实例。
作为奖励,我们正在使用 VirtualizingStackPanel,它不会渲染屏幕外的项目 - 如果您的数据库很大,这会派上用场。
作为主控件的DataContext的viewmodel需要定义:
public ObservableCollection<ResellerInfo> Resellers
ResellerInfo 是一个具有属性的类:
public String ResellerName
public ObservableCollection<CarInfo> Cars
CarInfo 是一个具有属性的类:
public String Model
public String Year
所有属性的setter都需要调用
NotifyPropertyChanged();
在INotifyPropertyChanged接口中定义
XAML:
<ItemsControl ItemsSource="{Binding Resellers}" >
<!-- Template specifies how this ItemsControl looks like -->
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<ScrollViewer Margin="5">
<ItemsPresenter />
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
<!-- ItemsPanel holds items. Use it to change the way items are laid out -->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<!-- ItemTemplate specifies how each item is displayed -->
<ItemsControl.ItemTemplate>
<DataTemplate>
<!-- BEGINNING OF SINGLE ITEM CODE -->
<StackPanel>
<TextBlock Text="{Binding ResellerName}" />
<ItemsControl ItemsSource="{Binding Cars}">
<!-- Template specifies how this ItemsControl looks like -->
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<ScrollViewer Margin="5">
<ItemsPresenter />
</ScrollViewer >
</ControlTemplate>
</ItemsControl.Template>
<!-- ItemsPanel holds items. Use it to change the way items are laid out -->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<!-- ItemTemplate specifies how each item is displayed. -->
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Model}" />
<TextBlock Text="{Binding Year}" />
</StackPanel>
<DataTemplate>
</ItemsControl.ItemTemplate> -->
</ItemsControl>
</StackPanel>
<!-- END OF SINGLE ITEM CODE -->
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我在 StackOverflow 上编写了代码,如果您发现错误,请随时纠正!