Cleve Cleve - 1 month ago 14
C# Question

Alignment issues using StackPanel in ListView.ItemsPanel in WPF

I want to display a collection of Teams going horizontally, with the Players in each Team going down. To achieve this I have a ListView (lvwTeams) bound to a collection of Teams. I change the lvwTeams.ItemsPanel to a StackPanel with its orientation set to Horizontal. The ItemTemplate is changed to contain another ListView (lvwPlayers), which is bound to the Players collection of the Team.

All is working, but the controls defined in the ItemTemplate appear in the middle of the StackPanel. Is there any way I can get lblTeamName positioned at the top, with lvwPlayers positioned underneath this, but filling the remaining area given by the StackPanel?

Here's the XAML:

<ListView x:Name="lvwTeams" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding Teams}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ListView.ItemsPanel>

<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label x:Name="lblTeamName" Grid.Row="0" Content="{Binding Name}"/>
<ListView x:Name="lvwPlayers" Grid.Row="1" ItemsSource="{Binding Players}" >
<ListView.ItemTemplate>
<DataTemplate>
<Label Content="{Binding FullName}"/>
</DataTemplate>
</ListView.ItemTemplate>

</ListView>
</Grid>

</DataTemplate>
</ListView.ItemTemplate>
</ListView>


Many thanks in advance for any help.

Answer

Try putting stretch on the content of the ListView, like this:

        <ListView x:Name="lvwTeams" 
              Grid.Row="1" 
              Grid.Column="1" 
              ItemsSource="{Binding Teams}"
              HorizontalContentAlignment="Stretch" 
              VerticalContentAlignment="Stretch">

And put * on the Second Row of the grid, to stretch the second ListView.

<ListView.ItemTemplate>
     <DataTemplate>
         <Grid>
           <Grid.RowDefinitions>
               <RowDefinition Height="Auto"/>
               <RowDefinition Height="*"/>
           </Grid.RowDefinitions>