说明:在很多时候,我们需要用一个ListBox显示集合数据,当用户选择集合中的某一项时,需要在另一个地方把这一项的详细数据显示出来,那我们可以利用UserControl来显示详情,重写UserControl.ContentTemplate即可。
<Grid>
<ListBox x:Name="List1">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="150"></RowDefinition>
<RowDefinition Height="150"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text="{Binding RoomName}" Width="200" Height="100" Foreground="Black" Background="Red"></TextBlock>
<UserControl Grid.Row="1" x:Name="txt" Content="{Binding ElementName=lb,Path=SelectedItem,Mode=TwoWay}" Width="100" Height="100" Foreground="Black" Background="Red" HorizontalAlignment="Left" VerticalAlignment="Top">
<UserControl.ContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding StuName}"/>
</DataTemplate>
</UserControl.ContentTemplate>
</UserControl>
<Label Content="{Binding ElementName=lb,Path=SelectedItem}"/>
<ListBox x:Name="lb" Grid.Row="2" ItemsSource="{Binding students}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<ContentControl Content="{Binding StuId}" Tag="{Binding StuName}" Width="30" Height="30" x:Name="btn">
</ContentControl>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>